js 下载文件

发布于 2022-09-06 09:40:06 字数 130 浏览 39 评论 0

后台传文件流给我,我要怎么下载 post获取的文件流是不是不能通过window.location.href下载?如果能下载该怎么处理,这种情况下前端location.href好像不能下载。如果是get的话是不是location.href就能下载?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

仙气飘飘 2022-09-13 09:40:06

后来解决了,但是不知道为什么文件名是797bb297-60ea-4069-911b-04133ce2b313这种类型
后台的人是设置了Content-Disposition,前端是是使用了vue和vueResource,vueResource在请求的时候需要加一句Vue.http.options.responseType = 'arraybuffer',然后再对返回的数据流做如下处理

downloadFile(content) {
      let blob = new Blob([content], { type: 'application/vnd.ms-excel' }) //根据实际情况设置type
      let objUrl = URL.createObjectURL(blob)
      window.location.href = objUrl
    }
遮云壑 2022-09-13 09:40:06

我们项目中使用的。

export const downloadFile = (fileName, url) => {
  if (isIE()) {
    ieDown(url)
  } else {
    const aLink = document.createElement('a');
    const evt = document.createEvent('MouseEvents');
    // var evt = document.createEvent("HTMLEvents")
    evt.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    aLink.download = fileName;
    aLink.href = url;
    aLink.dispatchEvent(evt)
  }
};

const ieDown = url => {
  window.open(url)
};

const isIE = () => {
  const explorer = window.navigator.userAgent;
  return explorer.indexOf('MSIE') >= 0 || explorer.indexOf('Trident/7.0') >= 0 || explorer.indexOf('Edge') >= 0;
};
烂柯人 2022-09-13 09:40:06

两种方法(第二种貌似是后端加)
1.<a href="你的下载地址" download> 核心是download属性。
2.下载地址加header("Content-Disposition:attachment;filename=xxx"); 核心是header。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文