如何使用JavaScript强制下载

JavaScript

执行此操作的函数非常小,并且依赖于URL.createObjectUrl :

function downloadFile(data, fileName, type="text/plain") {
  // Create an invisible A element
  const a = document.createElement("a");
  a.style.display = "none";
  document.body.appendChild(a);
  // Set the HREF to a Blob representation of the data to be downloaded
  a.href = window.URL.createObjectURL(
    new Blob([data], { type })
  );
  // Use download attribute to set set desired file name
  a.setAttribute("download", fileName); 
  // Trigger the download by simulating click
  a.click();
  // Cleanup
  window.URL.revokeObjectURL(a.href);
  document.body.removeChild(a);
}

  该函数将<a>元素注入到正文中,将其URL设置为目标文件的文本内容的Blob值,然后单击该元素以触发下载。该元素在此过程中保持隐藏状态,并在click()调用后立即从DOM中删除。调用该函数后,将立即显示浏览器的下载提示。更多内容可关注web前端开发信息

posted @ 2020-10-27 18:23  summer_xbc  阅读(792)  评论(0)    收藏  举报