纯前端下载文件的方法

真的查阅了很多资料,目前知道需要下载文件的url。需要纯前端下载文件,使用a标签的方法,对于浏览器会直接打开,而不是下载文件,而download属性不支持ie11. 问个纯前端下载文件的方法,可兼容现代浏览器,兼容IE11和以上版本。

阅读 9.9k
6 个回答

把我们项目中使用的代码直接给你吧!

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;
};

用iframe解决吧 创建一个iframe 设置src为url,append到页面上即可

有能 IE下不打开文件,直接下载的方法吗?

window.location.href = url;

有多个文件呢?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题