文件上传下载接口
![](https://img.haomeiwen.com/i15338236/1ba449679e9084a6.jpg)
文件上传
首先确保你引入了 web starter 配置文件上传大小限制
# 文件上传配置
# 最大支持文件大小 即单个文件大小 这里的单位是bytes 下面是5M
spring.servlet.multipart.max-file-size=5242880
# 最大支持请求大小 即一次性上传的总文件大小 这里的单位是bytes 下面是10M
spring.servlet.multipart.max-request-size=10485760
编写控制层传文件
@RestController
public class FileUploadController {
private static final Logger log =
LoggerFactory.getLogger(FileUploadController.class);
@PostMapping("/upload")
public String upload(@RequestParam MultipartFile file) throws IllegalStateException, IOException {
// 判断是否为空文件
if (file.isEmpty()) {
return "上传文件不能为空";
}
// 文件类型
String contentType = file.getContentType();
// springmvc处理后的文件名
String fileName = file.getName();
log.info("服务器文件名:" + fileName);
// 原文件名即上传的文件名
String origFileName = file.getOriginalFilename();
// 文件大小
Long fileSize = file.getSize();
// 保存文件
// 可以使用二进制流直接保存
// 这里直接使用transferTo
file.transferTo(new File("D:\\temp\\download\\", origFileName));
return String.format(file.getClass().getName() + "方式文件上传成功!\n文件名:%s,文件类型:%s,文件大小:%s", origFileName, contentType, fileSize);
}
}
![](https://img.haomeiwen.com/i15338236/a84140d0ad100851.png)
![](https://img.haomeiwen.com/i15338236/60a2130df4535fb2.png)
文件下载
确保引入 web starter 使用ResponseEntity方式进行下载
@GetMapping("/download")
public ResponseEntity<InputStreamResource> downloadFile(Long id)
throws IOException{
String filePath="D:\\documents\\photo\\secondary\\20200405/"+id+".jpg";
FileSystemResource file=new FileSystemResource(filePath);
HttpHeaders headers=new HttpHeaders();
headers.add("Cache-Control","no-cache, no-store, must-revalidate");
headers.add("Content-Disposition",String.format("attachment; filename=\"%s\"",file.getFilename()));
headers.add("Pragma","no-cache");
headers.add("Expires","0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
}
test
完美下载图片一张
网友评论