1. 用 a 标签
降龙第一式:《万物归一》
<a href="http://xxxxx">点击下载</a>
但是有时url不一定带有下载属性,浏览器会默认将其在线打开
<a href="http://xxxxx" download="文件名.txt">点击下载</a>
download 属性可以定义文件名,或带文件格式
降龙第二式:《无中生有》
const fileUrl = 'http://xxxxxx'
const fileName = `我下载的文件名称`;
const a = document.createElement('a');
a.href = fileUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
思路:创建 a 标签,添下载属性,追加到 DOM 里面,js 触发点击事件后,去掉 a 元素;
2. window.open(url)
1. 用 a 标签
降龙第一式:《万物归一》
<a href="http://xxxxx">点击下载</a>
但是有时url不一定带有下载属性,浏览器会默认将其在线打开
<a href="http://xxxxx" download="文件名.txt">点击下载</a>
download 属性可以定义文件名,或带文件格式
降龙第二式:《无中生有》
const fileUrl = 'http://xxxxxx'
const fileName = `我下载的文件名称`;
const a = document.createElement('a');
a.href = fileUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
思路:创建 a 标签,添下载属性,追加到 DOM 里面,js 触发点击事件后,去掉 a 元素;