通过文件流下载、预览图片,以及导出Excel表格
程序员文章站
2022-06-27 18:54:42
一、通过文件流下载图片1.接口为get方法使用window.location或a标签的src直接接收接口地址2.接口为post方法// url为获取文件流地址,payload为接口参数,fileName为图片名称axios.post(url, payload, { responseType: 'blob'}) .then(res => { let b = new Blob([res.data]); let url = URL.createObjectURL(b)...
一、通过文件流下载图片
1.接口为get方法
使用window.location或a标签的src直接接收接口地址
2.接口为post方法
// url为获取文件流地址,payload为接口参数,fileName为图片名称
axios.post(url, payload, {
responseType: 'blob'
})
.then(res => {
let b = new Blob([res.data]);
let url = URL.createObjectURL(b);
let link = document.createElement('a');
link.download = fileName;
link.href = url;
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(link.href);
document.body.removeChild(link);
}).catch(error => {
console.log(error);
})
二、通过文件流预览图片
// url为接口+参数
axios.get(url, {responseType: "arraybuffer",}).then(res => {
return 'data:image/png;base64,' + btoa(
new Uint8Array(res.data)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
);
})
.then(data => {
let newPage = window.open("", '_blank');
let img = new Image();
img.src = data;
img.style.width = "50%";
img.style.display = "block";
img.style.margin = "100px auto";
newPage.document.body.appendChild(img);
}).catch(error => {
console.log(error);
})
三、导出Excel表格
axios.get({url, {responseType: 'blob'}).then(res => {
let link = document.createElement('a');
let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
link.style.display = 'none';
link.href = URL.createObjectURL(blob);
link.setAttribute('download', Date.now() + '.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}).catch(error => {
console.log(error);
})
本文地址:https://blog.csdn.net/Dalin0929/article/details/109613608
下一篇: Java 十大排序算法之插入排序刨析