-
必要前提
-
form表单的enctype取值必须是multipart/form-data。enctype的功能是请求正文的类型
-
method必须是post
-
需要有<input type="file" />标签
-
使用commons-fileupload组件实现文件,需要导入该组件相应的支撑jar包
-
commons-fileupload-1.3.1.jar
-
commons-io-2.4.jar
-
<!-- 文件上传组件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
<form action="user/upload" method="post" enctype="multipart/form-data"> <input type="file" name="avatar" /> <input type="submit" value="上传" /> </form>
-
-
传统方式上传文件
-
先定义好文件上传的目录,这里的目录是指项目部署的目录,而不是项目文件的目录
-
获取文件上传项,用文件上传项对象解析request,返回文件项集合
-
遍历文件项,获取相关属性并完成上传
import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.List; import java.util.UUID; @Controller @RequestMapping(value="user") public class UserController{ @RequestMapping(value="upload") public String upload(HttpServletRequest request) throws Exception { //先创建文件上传的目录,这里目录是部署的目录 String path = request.getSession().getServletContext().getRealPath("/uploads"); File file = new File(path); //判断文件目录是否存在 if(!file.exists()){ file.mkdirs(); } //获取上传文件项 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); //解析request,解析时会产生异常,在方法外抛出异常 List<FileItem> fileItems = servletFileUpload.parseRequest(request); for(FileItem fileItem : fileItems){ if(fileItem.isFormField()){ //这里处理普通的表单项,如text、password等input标签 }else{ //这里处理上传文件项 //获取文件名称 String filename = fileItem.getName(); //使用UUID生成唯一标识的文件名称 String uuid = UUID.randomUUID().toString().replace("-", ""); filename = uuid+"_"+filename; //上传文件 fileItem.write(new File(path, filename)); //可以删除临时文件 fileItem.delete(); } } return "user"; } }
-