AWebMan

Menu

【英】Force Download with JavaScript

前言

今天这篇是实现一个由前端实现下载功能的文章,本文由@David Walsh 分享。

正文从这开始~~

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!

The JavaScript

The function to do this is quite small and relies on 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
 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.

Demo

<form onsubmit="onFormSubmit(); return false;">
   
<p>
       
<label for="demo_filename">File name:</label><br />
       
<input type="text" id="demo_filename" />
   
</p>
   
<p>
       
<label for="demo_content">Content:</label><br />
       
<textarea id="demo_content"></textarea>
   
</p>
   
<button type="submit">Download</button>
</form>
function onFormSubmit() {
   downloadFile
(
       document
.getElementById("demo_content").value,
       document
.getElementById("demo_filename").value
   
);
}

关于本文
作者:David Walsh
原文:https://davidwalsh.name/javascript-download

最后,为你推荐

【第874期】如何用 JavaScript 下载文件

【第1489期】关于JavaScript, NPM官方发布了2018年的回顾以及2019年的预测

本文源自微信公众号:前端早读课

— 于 共写了1854个字
— 文内使用到的标签:

评论已关闭。

%d 博主赞过: