前端代码片段

发布时间 2023-06-08 18:16:55作者: 黄河大道东

JS浏览器环境文件下载工具

/**
 * JS浏览器环境文件下载
 *
 * @param {Blob} data 二进制数据
 * @param {string} filename 保存的文件名称
 * @param {string} type 文件类型
 */
function download(data, filename, type) {
  const file = new Blob([data], {type: type});
  if (window.navigator.msSaveOrOpenBlob) {
    // IE10+ 浏览器
    // https://blog.csdn.net/weixin_37704921/article/details/84324923
    window.navigator.msSaveOrOpenBlob(file, filename);
  } else {
    // 其它浏览器
    const a = document.createElement("a")
    const url = URL.createObjectURL(file);
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    setTimeout(function () {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 0);
  }
}