itstrive / striveCode

some demo and js Knowledge points records :cn: :cloud: :snowflake:
108 stars 83 forks source link

前端实现文件下载 #21

Open itstrive opened 4 years ago

itstrive commented 4 years ago

使用a标签实现文件下载

<a href="http://somehost/somefile.zip" download="filename.zip">Download file</a>

使用 fetch(ajax) 实现文件下载

其实就是用fetch去模拟a标签的下载过程。

fetch('http://somehost/somefile.zip').then(res => res.blob()).then(blob => {
    var a = document.createElement('a');
    var url = window.URL.createObjectURL(blob);
    var filename = 'myfile.zip';
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
}))