前端进行文件下载
1、通过XMLHttpRequest获取文件流
2、生成a标签,href为文件流,浏览器直接就是下载文件
3、注意:跨域文件不能下载
var outputFile = function (content, filename) {
var eleLink = document.createElement('a');
eleLink.download = filename;
eleLink.style.display = 'none';
var blob = new Blob([content]);
eleLink.href = URL.createObjectURL(blob);
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
};
function urlToBlob(the_url, callback) {
let xhr = new XMLHttpRequest();
xhr.open("get", the_url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status == 200) {
if (callback) {
callback(this.response);
}
}
};
xhr.send();
}
function downloadFile(url){
urlToBlob(url, (res)=>{
outputFile(res, url.slice(url.lastIndexOf('/')+1))
})
}
demo地址 https://yuan30-1304488464.cos.ap-guangzhou.myqcloud.com/blog/other/%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD.html