前端通过 a 标签下载本地文件、跨域文件
在浏览器中直接打开静态 html 页面
download
设置无效- 能被浏览器打开的文件会直接被打开 图一
图二
点击下载后的效果:
VSCode上通过插件打开 html 页面
不跨域的情况:
download
设置有效- 文件会被正常下载
跨域的情况:
download
设置无效- 图片等能被浏览器直接打开的资源会在浏览器中直接打开,而没有被下载成文件
代码
点击下载后的效果:
跨域下载图片,会被浏览器直接打开
a
标签跨域下载文件实现
下载 .xlsx 文件
代码实现
<body>
<button onclick="download()">下载(跨域)</button>
<script>
function download() {
var url = 'http://scdn.gongyi.qq.com/quiz/Exam-Template.xlsx';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // 异步
xhr.responseType = 'blob'; // blob 类型
xhr.onload = function () {
if (xhr.status != 200) {
alert('下载异常!');
return;
}
if (window.navigator.msSaveOrOpenBlob) {
// IE
navigator.msSaveBlob(xhr.response, filename);
} else {
var newUrl = window.URL.createObjectURL(xhr.response);
var a = document.createElement('a');
a.setAttribute('href', newUrl);
a.setAttribute('target', '_blank');
a.setAttribute('download', '模板文件.xlsx'); // 自定义文件名(有效)
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
};
xhr.send();
}
</script>
</body>
点击下载后的效果:
下载图片
代码实现
<script>
...
var url = 'https://new.inews.gtimg.com/tnews/d8c3cb72/10f0/d8c3cb72-10f0-4a23-a094-3bfc5b0d60b9.png';
...
a.setAttribute('download', '涂鸦.png');
...
</script>
点击下载后的效果:
转载自:https://juejin.cn/post/6985087489547436045