一、 通过二进制流(Blob)下载
1 、API请求时候带上类型
export function download(fphm) {
return axios({
url: "/ynpst/download-invoice?fphm=" + fphm,
method: 'get',
responseType: 'blob'
})
}
2、文件预览和下载
seeItem(fphm) {
preview(fphm).then(res => {
const blob = new Blob([res], {
type: 'application/pdf;chartset=UTF-8'
})
let blobUrl = window.URL.createObjectURL(blob)
window.open(blobUrl)
})
},
dowload(fphm) {
download(fphm).then(res => {
this.downloadFn(res)
})
},
downloadFn(flow) {
if (!flow) return
const blob = new Blob([flow])
const blobUrl = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.download = '发票.pdf'
a.href = blobUrl
a.click()
}
二、通过文件地址Url下载文件
1、预览
window.open(fileUrl)
或者使用 a 标签
2、下载
调用downLoad方法下载文件,以下是具体方法:
function getBlob(url) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
url = url + `?r=${Math.random()}`;
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
}
function saveAs(blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
const anchor = document.createElement("a");
const body = document.querySelector("body");
anchor.href = window.URL.createObjectURL(blob);
anchor.download = filename;
console.log(filename, "filename");
anchor.style.display = "none";
body.appendChild(anchor);
anchor.click();
body.removeChild(anchor);
window.URL.revokeObjectURL(anchor.href);
}
}
export async function download(url, newFilename) {
const blob = await getBlob(url);
console.log(blob,'blob');
saveAs(blob, newFilename);
}