前端Ajax接收文件流,实现下载excel文件并解决乱码问题

后端(express):

Access-Control-Expose-Headers:暴露响应头供前端使用(Content-Disposition)

router.post("/downExcel", (req, res) => {
  let assetsPath = path.resolve(__dirname, "../assets/1.xlsx");
  res.set("Access-Control-Expose-Headers", "Content-Disposition");
  // res.set("Content-Type", "application/vnd.ms-excel");
  res.set("Content-Type", "application/octet-stream");
  res.set("Content-Disposition", `attachment; filename=mino.xlsx`);
  fs.createReadStream(assetsPath).pipe(res);
});

前端:

1. 原生XHR版

let xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("post", "http://127.0.0.1:8080/download/downExcel", true);
xhr.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    let [_, fileName] = this.getResponseHeader(
      "Content-Disposition"
    ).match(/filename=(.*)$/);
    let blob = new Blob([xhr.response], {
      type: "application/vnd.ms-excel",
    });
    let link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
  }
};
xhr.send();

2. jQuery版

$.ajax({
  method: "post",
  url: "http://127.0.0.1:8080/download/downExcel",
  xhrFields: {
    responseType: "arraybuffer",
  },
  success: function (res, _, xhr) {
    let [, fileName] = xhr
      .getResponseHeader("Content-Disposition")
      .match(/filename=(.*)$/);
    let blob = new Blob([res], {
      type: "application/vnd.ms-excel",
    });
    let link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
  },
});

进阶:使用断点续传下载、上传文件 – 206

Q:使用swagger-ui请求接口,返回的文件没有乱码,一旦使用jQuery接收文件流,获取的excel有乱码:

A:      设置responseType时格式错误;要使用xhrFields。

$.ajax({
    ...
    responseType: 'blob' // 无效
    ...
})

 

    原文作者:MINO吖
    原文地址: https://blog.csdn.net/qq_36157085/article/details/110323364
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞