Springboot提供檔案的上傳、下載下傳、預覽接口
檔案上傳
@PostMapping("/upload/tocheckfile")
public JSONObject upload(@RequestPart("uploadFile") MultipartFile file){
JSONObject response = new JSONObject();
try {
FilesUtils.uploadFile(file, toCheckFileDir);
response.put("code", 2000);
} catch (Exception e) {
e.printStackTrace();
log.error("上傳檔案出現異常!");
response.put("code", 5000);
response.put("error", "上傳檔案失敗, e"+e.toString());
}
return response;
}
public static void uploadFile(MultipartFile file, String filePath) {
File toFile = new File(filePath + file.getOriginalFilename());
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(toFile);
IOUtils.copy(file.getInputStream(), fileOutputStream);
log.info("file:{} upload succ !", file.getOriginalFilename());
}catch (Exception e){
e.printStackTrace();
log.error("file:{} upload failed!", file.getOriginalFilename());
}finally {
try {
fileOutputStream.close();
}catch (Exception e){
log.error("關閉fileOutputStream 發生異常,\n e:{}", e);
}
}
}
檔案下載下傳或者預覽
檔案下載下傳和預覽可以使用相同接口,前端代碼做調整即可
@PostMapping("/download")
public ResponseEntity<byte[]> download(@RequestBody JSONObject params){
try{
String filePath = params.getString("filePath");
return FilesUtils.download(filePath);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static ResponseEntity<byte[]> download(String filepath) throws Exception{
File file = new File(filepath);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentDispositionFormData("attachment",
new String(file.getName().getBytes(StandardCharsets.UTF_8), "utf-8"));// 部分浏覽器需要将"utf-8"改"為ISO8859-1",否則會出現檔案名中文亂碼
httpHeaders.add("Access-Control-Expose-Headers", "Content-Disposition");
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 擷取檔案的字元數組
byte[] content = FileUtils.readFileToByteArray(file);
return new ResponseEntity<>(content, httpHeaders, HttpStatus.OK);
}