大概都是用接口直接掉用,然后获取到blob参数来进行直接下载的
方法一、fetch调用
fetch(放要下载的url).then(async res => await res.blob()).then((blob) => {
const a = document.createElement('a');
a.style.display = 'none';
a.href = URL.createObjectURL(blob);
a.download = 放要下载的名字;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
方法二、XMLHttpRequest
/**
* 获取页面文件名
* @param url 文件url
*/
function downloadUrlFile(url) {
url= url.replace(/\\/g, '/');
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
//xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
xhr.onload = () => {
if (xhr.status === 200) {
// 获取文件blob数据并保存
var fileName = getFileName(url);
saveAs(xhr.response, fileName);
}
};
xhr.send();
}
/**
* URL方式保存文件到本地
* @param data 文件的blob数据
* @param name 文件名
*/
function saveAs(data, name) {
var urlObject = window.URL || window.webkitURL || window;
var export_blob = new Blob([data]);
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
save_link.href = urlObject.createObjectURL(export_blob);
save_link.download = name;
save_link.click();
}
/**
* 根据文件url获取文件名
* @param url 文件url
*/
function getFileName(url)
{
var num = url.lastIndexOf('/')+1
var fileName = url.substring(num)
//把参数和文件名分割开
fileName = decodeURI(fileName.split("?")[0]);
return fileName;
}
方法三、axios
function downloadFile(url, fileName = '', requestConfig = {}) {
return Axios.get(url, requestConfig)
.then(resp => {
if (resp.status !== 200) {
throw new Error('Download failed.')
} else if (resp.blob) {
return resp.blob()
} else {
return new Blob([resp])
}
})
.then(blob => URL.createObjectURL(blob))
.then(url => {
downloadURL(url, fileName)
URL.revokeObjectURL(url)
})
}