Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端实现文件下载 #21

Open
itstrive opened this issue Sep 24, 2019 · 0 comments
Open

前端实现文件下载 #21

itstrive opened this issue Sep 24, 2019 · 0 comments
Labels
js About Js something

Comments

@itstrive
Copy link
Owner

使用a标签实现文件下载

<a href="http://somehost/somefile.zip" download="filename.zip">Download file</a>
  • href: 下载地址
  • download: 文件名

使用 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);
}))
  • 使用 createObjectURL 方法转化成 ObjectURL,等同于一个下载地址链接
  • 通过 revokeObjectURL 回收 ObjectURL
@itstrive itstrive added the js About Js something label Sep 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js About Js something
Projects
None yet
Development

No branches or pull requests

1 participant