首页 > 编程语言 > 详细

如何使用JavaScript强制下载

时间:2020-10-27 20:36:12      阅读:35      评论:0      收藏:0      [点我收藏+]

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前端开发信息

如何使用JavaScript强制下载

原文:https://www.cnblogs.com/summerxbc/p/13886443.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!