浏览器打开文件url直接下载

前端:

通过给A标签加download属性,其value为文件名

同步

1
<a href="xxx/xxx/xx.xx" download="filename">

异步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//谷歌,360极速等浏览器下载
function download(src) {
// 创建隐藏的可下载链接
var eleLink = document.createElement('a');
eleLink.download = src;
eleLink.style.display = 'none';
// // 字符内容转变成blob地址
eleLink.href = src;
// // 触发点击
document.body.appendChild(eleLink);
eleLink.click();
// // 然后移除
document.body.removeChild(eleLink);
};

服务端:

设置响应头Content-Disposition

1
Content-Disposition: attachment; filename="filename.jpg"

nos通过url query的download参数来实现:

1
window.location.href = 'http://url?download=filename.jpg'

参考链接:

坚持原创技术分享,您的支持将鼓励我继续创作!