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

本文介绍如何利用文件流实现图片下载及预览、Excel表格导出等功能。涵盖了GET与POST请求方式,详细展示了使用axios进行文件流处理的具体代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、通过文件流下载图片
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);
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值