上传文件
默认情况下springboot不需要做任何配制即可完成上传文件,但有可能因默认配置不符而导致文件上传失败问题,所以了解相关配置信息更有助于我们对问题的定位和修复;
配制
# 是否支持批量上传 (默认值 true)
spring.servlet.multipart.enabled=true
# 上传文件的临时目录 (一般情况下不用特意修改)
spring.servlet.multipart.location=
# 上传单个文件最大为 1M (默认值 1M 根据自身业务自行控制即可)
spring.servlet.multipart.max-file-size=1048576
# 上传所有文件总最大为 10M(默认值10M 根据自身业务自行控制即可)
spring.servlet.multipart.max-request-size=10485760
# 文件大小阈值,当大于这个阈值时将写入到磁盘,否则存在内存中,(默认值0 一般情况下不用特意修改)
spring.servlet.multipart.file-size-threshold=0
# 判断是否要延迟解析文件(相当于懒加载,一般情况下不用特意修改)
spring.servlet.multipart.resolve-lazily=false
前端代码
<h2>单一文件上传示例</h2>
<div>
<form method="POST" enctype="multipart/form-data" action="/uploads/singleUpload">
文件1:<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
</div>
<hr/>
<h2>批量文件上传示例</h2>
<div>
<form method="POST" enctype="multipart/form-data"
action="/uploads/multiUpload">
文件1:<input type="file" name="file"/>
文件2:<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
</div>
后端代码:
@PostMapping("/singleUpload")
@ResponseBody
public Map<String, String> singleUpload(@RequestParam("file") MultipartFile file) throws Exception {
log.info("[文件类型] - [{}]", file.getContentType());
log.info("[文件大小] - [{}]", file.getSize());
file.transferTo(new File("F:\\test\\" + file.getOriginalFilename()));
Map<String, String> result = new HashMap<>(2);
result.put("contentType", file.getContentType());
result.put("fileName", file.getOriginalFilename());
result.put("fileSize", file.getSize() + "");
return result;
}
@PostMapping("/multiUpload")
@ResponseBody
public List<Map<String, String>> multiUpload(@RequestParam("file") MultipartFile[] files) throws Exception {
if (files == null || files.length == 0)return null;
List<Map<String, String>> results = new ArrayList<>();
for (MultipartFile file : files) {
file.transferTo(new File("F:\\test\\" + file.getOriginalFilename()));
Map<String, String> map = new HashMap<>(2);
map.put("contentType", file.getContentType());
map.put("fileSize", file.getSize() + "");
result.put("fileName", file.getOriginalFilename());
results.add(map);
}
return results;
}
常见问题
在项目开发中,一直是正常的,上传了个文件突然就报错了,报错信息如下:
Caused by: java.io.IOException: The temporary upload location [C:\Users\admin\AppData\Local\Temp\tomcat.8572785615189560421.8080\work\Tomcat\localhost\ROOT] is not valid
经过一番辛苦的查找,原来是spring boot 内部上传文件临时存储路径不存在了,现在有两种办法:
-
第一种:配制
spring.servlet.multipart.location
这个属性 -
第二种:注入一个Bean,手动添设置下临时存储路径,代码如下:
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setLocation("d://temp");
return factory.createMultipartConfig();
}
下载文件
在springboot里,我们下载文件除了传统模式的将文件流写入到response,然后实现下载之外还可以通过ResponseEntity来实现:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<FileSystemResource> download(Integer id) {
File file = new File("c:\\test"+id+".xls")
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new FileSystemResource(file));
}