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 類的常量