下载cdn上pdf协议的方法
word和excel类文件均适用
开发中遇到一个问题,cdn上的pdf能在浏览器直接打开,但是使用a标签不能直接下载,解决方法如下
fetch下载
function download (url,fileName){
fetch(url,{
method: 'get',
responseType: 'blob'//'arraybuffer' 文件流类型
}).then(res => {
return res.blob();
}).then(blob => {
let bl = new Blob([blob], {type: "application/pdf;chartset=UTF-8"});//表示下载文档为pdf,如果是word则设置为msword,excel为excel
// "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"切换文件类型 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
fileName = fileName;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
})
}
axios下载
function dowanloadpdf(Url, filename) {
axios({
method: 'get',
url: Url,
responseType: 'blob'
}).then(function (response) {
const link = document.createElement('a');
let blob = new Blob([response.data], { type: response.data.type });
let url = URL.createObjectURL(blob);
link.href = url;
link.download = filename;
link.click();
});