Spring Boot 文件处理
对于文件上传或者下载,我们需要关注是Request Headers 或 Response Headers 中的Content-type 属性
文件上传
对于文件上传,必须使用 MultipartFile 作为请求参数并且api中consume属性要为 MULTIPART_FORM_DATA_VALUE 。代码如下
@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String fileUpload(@RequestParam("file") MultipartFile file) {
return null;
}
完整的代码如下
@RestController
public class FileUploadController {
@RequestMapping(value = "/upload", method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
File convertFile = new File("/var/tmp/"+file.getOriginalFilename());
convertFile.createNewFile();
FileOutputStream fout = new FileOutputStream(convertFile);
fout.write(file.getBytes());
fout.close();
return "File is upload successfully";
}
}
通过PostMan来测试,需要主要的是:设置请求头head的Content-Type:multipart/form-data;填写body选择form-data,然后选择文件。详细步骤可以参考:这里
文件下载
文件下载
对于文件下载,要InputStreamResource类来下载文件。我们需要设置响应头的Content-Disposition的key并且还要明确响应是多媒体类型。
public ResponseEntity<Object> downloadFile() throws IOException{
String filename = "/var/tmp/mysql.png";
File file = new File(filename);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
header.add("Prama", "no-cache");
header.add("Expires", "0");
}
完整代码如下
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<Object> downFile() throws FileNotFoundException {
String filename = "/var/tmp/aa.txt";
File file = new File(filename);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
ResponseEntity responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length()).
contentType(MediaType.parseMediaType("application/txt")).body(resource);
return responseEntity;
}
关于更多Content-type的内容,请参考:这里
也可以查看 org.springframework.util.MimeTypeUtils 类的常量