前提工作
- 给
form
表单添加属性。enctype = enctype="multipart/form-data"
- 将表单提交方式改成
post
请求 - 给表单下通过
<input>
标签添加一项文件上传框 - 导包
commons-io.2.4
commons-fileupload.1.3.1
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
传统文件上传
- 获取要上传的位置
- 判断文件目录是否存在。
- 解析request对象。获取上传文件项
- 解析request
- 判断是普通项还是文件项
如果是文件项
- 获取文件名字
- 通过上传的名字,加载到需要上传的位置
- 关闭临时文件
@RequestMapping(value = "/testFile")
public String testFile(HttpServletRequest request){
String path = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(path);
if(!file.exists()){
file.mkdir();
}
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
try {
List<FileItem> list = servletFileUpload.parseRequest(request);
for(FileItem i : list){
if(i.isFormField()){
System.out.println(i.getString("UTF-8"));
}else{
String filename = i.getName();
i.write(new File(path,filename));
i.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
Spring MVC 文件上传

- 配置文件解析器
注意事项:
bean
对象的id
属性值必须是multipartResolver
- 获取要上传的位置
- 判断文件目录是否存在
- 根据文件名,上传到指定位置
@RequestMapping(value = "/testFileload")
public String testFileload(HttpServletRequest request, MultipartFile upload) throws IOException {
String path = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(path);
if(!file.exists()){
file.mkdir();
}
String filename = upload.getOriginalFilename();
upload.transferTo(new File(path,filename));
return "success";
}