SpringBoot專案中檔案上傳與下載?

語言: CN / TW / HK

 

一、檔案上傳

@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 #總檔案上傳限制