大飞_dafei

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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   大飞_dafei  阅读(2900)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2020-05-01 vue组件之间传值(01)__父组件传值子组件 props _fei
2020-05-01 高阶函数 filter map reduce _fei
点击右上角即可分享
微信分享提示