Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )
1. The link to download the file
//该方法火狐有些版本是不支持的
window.location.href=url
//为了解决火狐有些版本不支持,可以改成这种方式
window.location=url
//该方法在火狐上没有效果的,在IE浏览器上是可以的
window.open(url, '_blank') // 打开新窗口
- Advantages: good compatibility, concise code;
- Disadvantages:
- URL length limited;
- Time to get this process back-end processing, interactive and do not progress according to the callback function tips
2. iframe Download file
try {
const elemIF = document.createElement('iframe')
elemIF.src = url //url为后端返回路径
elemIF.style.display = 'none'
document.body.appendChild(elemIF)
// 防止下载两次
setTimeout(() => {
document.body.removeChild(elemIF)
}, 1000)
} catch (e) {
console.log(e)
}
- Advantages: good compatibility, concise code;
- Disadvantages:
- URL length limited;
- Back-end processing time to get this process, do not interact well according to schedule prompt callback function;
- URL length limited;
3. HTML5 download new property
This property is very important, it can specify the file name to download, and you can tell the browser to download the target link is a link, not a common link, we look at the code below you can see the difference:
<a href="data:text/txt;charset=utf-8,测试下载纯文本" download="测试.txt" >下载1</a>
<a href="data:text/txt;charset=utf-8,测试下载纯文本">下载2</a>
Can be found, Download button enables downloading, open the file in your browser when you click the download link directly 2.
Additional information:
file: /// mode seemingly does not take effect;
links to some third party link does not take effect, specifically to be studied;
4. The Blob object returned by the backend
function download(content, filename) {
// 字符内容转变成blob地址
var blob = new Blob([content]);
if('msSaveOrOpenBlob' in navigator){ //兼容IE
window.navigator.msSaveOrOpenBlob(blob, filename);
return;
}
var eleLink = document.createElement('a');
eleLink.download = filename;
$(eleLink).css('display', 'none');
eleLink.href = URL.createObjectURL(blob);
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
};
5. axios (ajax) The front end of the return data stream generating file downloads
axios.post(url, param, {
responseType: 'blob'
}).then((res) => {
console.log('res', res);
const blob = res.data;
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = (e) => {
const a = document.createElement('a');
a.download = `文件名称.zip`;
// 后端设置的文件名称在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"20181211191944.zip\"",
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
}).catch((err) => {
console.log(err.message);
});