对于想在浏览器中点击间接下载,而非在浏览器中预览的场景,实用的 JS 函数;
比方网页 txt 文件点击不预览间接下载
思路:创立 <a>
Element
,获取 blob
数据,利用 window.URL.createObjectURL()
读取并指定给 a.href
,插入 <body>
手动触发下载;
// 动态资源服务器地址
const staticServer = 'http://xx.xxx.xxx.xxx:xxxxx';
// 点击已上传的文件
function onPreview(file) {if (file && file.path) {let url = `${staticServer}${file.path}`
let isTxt = isFileType(file.path, 'txt');
// txt 间接下载,防止新窗口关上
if (isTxt) {let name = file.name || file.path.split('/').slice(-1)[0] || ''
exportFile(url, name)
} else {window.open(url)
}
}
},
// 判断文件类型
function isFileType(url, fileTypeList = '') {const type = url.split('.').at(-1);
if(Array.isArray(fileTypeList)){return fileTypeList.includes(type)
} else {return type === fileTypeList}
},
// 导出文件
function exportFile(url, fileName) {function createObjectURL(object) {return window.URL ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object)
}
let xhr = new XMLHttpRequest();
let formData = new FormData();
xhr.open('get', url);
xhr.setRequestHeader('Auth-User-Token', localStorage.getItem('token'));
xhr.responseType = 'blob';
xhr.onload = function (e) {if (this.status === 200) {
let blob = this.response;
let newFileName = `${fileName}`;
if (window.navigator.msSaveOrOpenBlob) {navigator.msSaveBlob(blob, newFileName)
} else {let a = document.createElement('a');
let url = createObjectURL(blob);
a.href = url;
a.download = newFileName;
document.body.append(a);
a.click();
window.URL.revokeObjectURL(url);
}
}
};
xhr.send(formData)
};
// 导出文件,不做兼容
const exportFile2 = (file) => {let link = document.createElement('a')
let url = staticServer + file.path
fetch(url).then(res => res.blob()).then(blob => {let urlObj = URL.createObjectURL(blob);
link.href = urlObj;
link.download = ''
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(urlObj);
})
};