一、文件上傳
@ApiOperation(value = "文件上傳", notes= "文件上傳")
@PostMapping("/upload")
public Result upLoadFile(@ApiParam(value = "選擇需要上傳的文件",required = true) MultipartFile file){
if (file.isEmpty()){
return Result.error(CodeMsg.ERROR);
}
String fileName = file.getOriginalFilename();
long size = file.getSize();
//控制檯打印文件信息
System.out.println(fileName+"-->"+size);
//拼接成新的文件名
int index = fileName.indexOf(".");
String suffix = fileName.substring(index);
String name = Date.valueOf(LocalDate.now())+suffix;
//指明文件上傳位置
File dest = new File(location, name);
//判斷文件父目錄是否存在
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdir();
}
try {
//寫入文件
file.transferTo(dest);
return Result.success();
} catch (IOException e) {
e.printStackTrace();
return Result.error(CodeMsg.ERROR);
}
}
二、文件下載
@ApiOperation(value = "文件下載", notes = "文件下載")
@GetMapping("/download")
public Result downLoadFile(@ApiParam(value = "填寫需要下載的文件") String fileName, HttpServletResponse response){
File file = new File(location, fileName);
if(file.exists()){
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
FileInputStream input = null;
try{
input = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
int real;
byte[] bytes = new byte[1024];
while((real=input.read(bytes))!=-1){
out.write(bytes, 0, real);
}
return Result.success();
}catch (Exception e){
e.printStackTrace();
return Result.error(CodeMsg.ERROR);
}
}
return Result.error(CodeMsg.ERROR);
}
三、配置文件
spring:
servlet:
multipart:
max-file-size: 100MB #單個文件最大限制
max-request-size: 100MB #總文件上傳限制