美文网首页
js下载后台传过来的流文件

js下载后台传过来的流文件

作者: coderfl | 来源:发表于2020-08-12 14:44 被阅读0次

前端js/vue下载后台传过来的流文件(如excel)并设置下载文件名
<a>标签下载文件重命名失败,download无效解决方案

//下载方法封装axios
export const GETFILE = (url, params) => {
  return new Promise((resolve, reject) => {
    axios({
      method: "get",
      url: `${base}${url}`,
      params: params,
      responseType: "blob" // 表明返回服务器返回的数据类型
    }).then(res => {
        resolve(res);
      })
      .catch(e => {
        reject(e);
      });
  });
};

//下载方法调用
      GETFILE(url, { planId }).then(value => {
        let blob = new Blob([value.data]);
        const fname = value.headers['content-disposition'].split('filename=')
        let fileName = fname[1];
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          let link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;//文件名的后缀可以解决文件类型问题
          link.click();
          // 释放内存
          window.URL.revokeObjectURL(link.href);
        }
      })

相关文章

网友评论

      本文标题:js下载后台传过来的流文件

      本文链接:https://www.haomeiwen.com/subject/xtzpdktx.html