文件上传与下载:
1,使用MultipartFile完成上传,Springboot是使用Servlet3中的Part对象完成上传,不是使用的fileupload;
2,上传相关配置:
spring.http.multipart.enabled=true:是否允许处理上传;
spring.http.multipart.maxFileSize=1MB:允许最大的单文件上传大小,单位可以是kb,mb;
spring.http.multipart.maxRequestSize=10MB:允许的最大请求大小;
3,也可以通过创建一个MultipartConfigElement类型的bean对上传进行配置:
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory mcf = new MultipartConfigFactory();
mcf.setMaxFileSize("1MB");
mcf.setMaxRequestSize("10MB");
return mcf.createMultipartConfig();
}
4,关于上传文件的处理:
因为应用是打成jar包,所以一般会把上传的文件放到其他位置,并通过设置
spring.resources.static-locations
来完成资源位置映射。
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:/Users/stef/devs/workspace/springboot-demo/upload/
例子,这里用@value注解来引入配置文件变量
application.properties中添加file.path=d:/upload/
Controller类
@Controller
public class FileController {
//由于项目会打成jar包,所以我们需要自定义盘符目录来上传
@Value("${file.path}")
private String filePath;
@RequestMapping("/upload")
@ResponseBody
public String upload(MultipartFile file) throws Exception {
//获取后缀名
String endName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String fileName = UUID.randomUUID().toString() + endName;
System.out.println(file);
FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(filePath+fileName)));
return fileName;
}
@RequestMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
File file =new File(filePath+"a.jpg");
InputStream in =new FileInputStream(file);
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="+"a.png");
ServletOutputStream out =response.getOutputStream();
FileCopyUtils.copy(in,out);
in.close();
out.close();
}
}
前端Form表格要设成 post,且mime类型要设成 multipart/form-data
文件上传:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>