欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

通过文件流下载、预览图片,以及导出Excel表格

程序员文章站 2022-03-18 22:35:16
一、通过文件流下载图片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