大飞_dafei

导航

SpringBoot中文件二进制流下载功能Api

SpringBoot中文件二进制流下载功能Api

Controller 中写方法, PostMappingGetMapping 都可以

方法一 通过ResponseEntity<InputStreamResource>实现

// 下载文件 PostMapping 和 GetMapping 都可以
@PostMapping("download")
// @GetMapping("download")
public ResponseEntity<InputStreamResource> download() throws IOException {

    // String filePath  = "E:\\self_web\\git_dev\\vue\\zFei_springBoot\\target\\001.png";
    String filePath  = "E:\\self_web\\git_dev\\vue\\zFei_springBoot\\target\\02.jpg";

    FileSystemResource file = new FileSystemResource(filePath);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");

    return ResponseEntity
            .ok()
            .headers(headers)
            .contentLength(file.contentLength())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(new InputStreamResource(file.getInputStream()));
}

方法二 通过HttpServletResponse的OutputStream实现

// 方法二
// 文件下载2  PostMapping 和 GetMapping 都可以
@PostMapping("download2")
// @GetMapping("download2")
public String download2(HttpServletRequest request, HttpServletResponse response) throws IOException {
    System.out.println("ddddddddd");

    String filePath = "E:\\self_web\\git_dev\\vue\\zFei_springBoot\\target\\";
    // String fileName = "001.png";
    String fileName = "02.jpg";
    response.setContentType("application/octet-stream");
    response.setHeader("content-type", "application/octet-stream");
    // 设置文件名  URLEncoder.encode(fei_name, "utf-8")
    response.setHeader("Content-Disposition", "attachment;fileName=" + "fei_name");
    response.setHeader("Access-Control-Allow-Origin", "*");

    FileInputStream fis = null;
    BufferedInputStream bis = null;
    try {
        File file = new File(filePath, fileName);
        byte[] buffer = new byte[1024];
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        ServletOutputStream os = response.getOutputStream();
        int i = bis.read(buffer);
        while (i != -1) {
            os.write(buffer, 0, i);
            i = bis.read(buffer);
        }
        System.out.println("success");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;

}

 

前端流处理

前端使用blob接受处理接口返回的流

get 方式

downloadGet(){
  axios.get("/api/download", {
    params: {fileId: 123},
    responseType: "blob", // 1.首先设置responseType对象格式为 blob: // 二进制流
  }).then((res) => {
    let blob = new Blob([res.data], {
      type: ' image/png',
      // type:' image/jpeg',
      // type: "application/vnd.ms-excel",
    }); // 获取请求返回的response对象中的blob 设置文件类型

    let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
    let a = document.createElement("a");
    a.href = url;
    a.download = "自定义文件名字.png";
    a.click();
    window.URL.revokeObjectURL(url);  //释放blob对象
  })
}
View Code

post 方式

downloadPost(){
  axios.post("/api/download",
      {fileId: 123},
      {responseType: "blob"} // 设置responseType对象格式为 blob:
  ).then((res) => {
    let blob = new Blob([res.data], {
      type: ' image/png',
      // type:' image/jpeg',
      // type: "application/vnd.ms-excel",
    }); // 获取请求返回的response对象中的blob 设置文件类型

    let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
    let a = document.createElement("a");
    a.href = url;
    a.download = "自定义文件名字.png";
    a.click();
    window.URL.revokeObjectURL(url); //释放blob对象
  })
}

 

posted on 2022-05-01 15:48  大飞_dafei  阅读(2811)  评论(0编辑  收藏  举报