1、需求
- .html,.text,.pdf...等文件通过a标签直接打开链接浏览器会默认打开;
- 业务需求通过文件链接地址直接打开文件,而不是打开
2、尝试
- 直接使用a标签,只支持excel,等文件直接下载,且无法设置下载文件名
function downloadFileByBlob(Url, filename) {
const eleLink = document.createElement('a')
eleLink.download = filename
eleLink.style.display = 'none'
eleLink.href = Url
// 触发点击
document.body.appendChild(eleLink)
eleLink.click()
URL.revokeObjectURL(Url) // 释放URL 对象
// 然后移除
document.body.removeChild(eleLink)
}
- 使用xhr请求,获取blob数据(会存在跨域,需要后端配合处理,较麻烦不推荐)
/**
* 获取页面文件名
* @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;
}
3、 具体实现
- 使用fetch,解决跨域,获取文件blob数据再下载,可以直接设置文件名
export function downloadName(url, filename) {
fetch(url, {
mode: 'no-cors', // 必要设置,解决跨域
}).then(async res => {
let blob = await res.blob()
return blob
}).then((blob) => {
const a = document.createElement('a')
a.style.display = 'none'
a.href = URL.createObjectURL(blob)
a.download = filename
a.target = '_blank'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
})
}