上传文件原理图
1.依赖的jar
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
2.配置文件解析器(注解方式)
@Bean
public MultipartResolver multipartResolver(){
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
//设置文件最大值
commonsMultipartResolver.setMaxUploadSize(1000000);
return commonsMultipartResolver;
}
2.上传后台代码
@RequestMapping("/upload")
@ResponseBody
public String upload( HttpServletRequest request, MultipartFile upload_file ) throws IOException {
String filePath = request.getSession().getServletContext().getRealPath("/upload");
File file = new File(filePath);
if(!file.exists()){
file.mkdir();
}
String fileName = upload_file.getOriginalFilename();
upload_file.transferTo(new File(filePath+"/"+fileName));
System.out.println(filePath+fileName);
return "success";
}
3.对比传统servlet上传优势:
多了文件解析器,就不用自己解析request啦!