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);
}