Skip to content

前端实现文件下载 #21

@itstrive

Description

@itstrive

使用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

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsAbout Js something

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions