通过文件流下载、预览图片,以及导出Excel表格
一、通过文件流下载图片
1.接口为get方法
使用window.location或a标签的src直接接收接口地址
1
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);
})
太 强 了!