使用JavaScript强制下载

Force download scripts have been an important part of internet usability for a long time.  I can attest to that by the number of times I've implemented this feature on the server side and the popularity of my PHP Force Download post, even to this day.  With the web world having moved much more the client side, I started looking for a method to force download without the need of a server, and I found it....right in the Firefox DevTools Debugger!

长期以来,强制下载脚本一直是Internet可用性的重要组成部分。 我可以通过在服务器端实现此功能的次数以及我的PHP Force Download帖子的流行程度证明这一点,直到今天。 随着网络世界在客户端方面的发展,我开始寻找一种无需服务器即可强制下载的方法,然后在Firefox DevTools Debugger中找到了它。

JavaScript (The JavaScript)

The function to do this is quite small and relies on URL.createObjectUrl:

执行此操作的函数非常小,并且依赖于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);
}

The function injects an <a> element into the body, sets it URL to a Blob value to the text content of the destination file, and clicks the element to trigger the download.  The element remains hidden during the process and is removed from the DOM immediately after the click() call.  As soon as the function is called, the browser's download prompt is displayed.

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

I look forward to learning more about both createObjectURL and Blob; those two are the true magic of this technique!

我期待学习有关createObjectURLBlob更多信息; 那两个才是这项技术的真正魔力!

Shout out to Sneha Jain for implementing this great technique within the Firefox DevTools debugger!

向Sneha Jain大喊,以在Firefox DevTools调试器中实现这项出色的技术!

翻译自: https://davidwalsh.name/javascript-download

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值