说明

web 页面中文件下载方式说明

参考

https://juejin.im/post/5bdd58db51882517217fb36d

方式

window.open

浏览器无法解析,它就会把该文件下载下来 。html、pdf、png 等则会打开打开新页签,不会自动下载。

1
2
3
4
5
function downFile(filepath) {
//项目路径+相对路径
window.open(filepath, "downfile");
return;
}

a 标签

不需要打开一个新的窗口,在当前窗口下实现下载。代表性的解决案例是:Github Docunload Zipdownload 属性为下载后生成的文件名称

1
2
3
<a href="https://xxx/file.zip" download="blog">
Download ZIP
</a>

动态创建 a 链接

创建一个 a 标签,添加 hrefdownload 属性,模拟用户点击,实现下载

1
2
3
4
5
6
7
8
9
10
11
12
13
const downloadFile = (url, fileName = '') => {
let eleLink = document.createElement('a');
eleLink.download = fileName;
eleLink.style.display = 'none';
eleLink.target = "_blank";
eleLink.href = url;
// 受浏览器安全策略的因素,动态创建的元素必须添加到浏览器后才能实施点击
document.body.appendChild(eleLink);
// 触发点击
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
};

下载 html 片段或者文本

1
2
3
4
5
6
7
8
9
const debug = ['<a id="a"><b id="b">hey!</b></a>'];
const blob = new Blob(debug,{
type: 'text/html'
})

const url = URL.createObjectURL(blob);

//使用
downloadFile(url, 'index.html');

图片是 base64 下载

1
2
3
4
5
6
7
8
const debug = ['base:...'];
const blob = new Blob(debug,{
type: 'text/html'
})

const url = URL.createObjectURL(blob);

downloadFile(url, 'index.html');

canvas 下载

1
2
3
4
5
6
7
8
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
...
...
...
const src = canvas.toDataURL('image/png')

downloadFile(src, 'canavs.png')