封装blob文件流下载方法

本文介绍了使用fetch和axios实现从URL下载Excel文件的方法,并展示了如何预览图片及将KML文件转换为GeoJSON格式的过程。

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

导出excel

  • fetch版

exportFn(url, folderName) {
    fetch(url, {
        method: 'get',
        responseType: 'blob'
    }).then(res => res.blob())
      .then(blob => {
        let a = document.createElement('a')
        // 获取 blob 本地文件连接 (blob 为纯二进制对象,不能够直接保存到磁盘上)
let url = window.URL.createObjectURL(newBlob([blob], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }));   
        a.href = url;
        //定义导出的文件名
        a.download = `${folderName}.xls`;  
        a.click();
        window.URL.revokeObjectURL(url);
    })
}
  • axios版

exportFn(url, folderName) {
axios({
    method: 'get',
    url: url,
    responseType: "blob"
}).then(res => {
    if (res.type === 'application/vnd.ms-excel') {
        const blob = newBlob([res]);
        const a = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        a.href = href;
        a.download = folderName + '.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(href);
    }
}).catch(function (error) {
    console.log(error);
});
}

图片预览

previewImg(url) {
    fetch(url, {
        method: 'get',
        responseType: 'blob'
    }).then(res => res.blob())
        .then(blob => {
        // 获取 blob 本地文件连接 (blob 为纯二进制对象,不能够直接保存到磁盘上)
let imgUrl = window.URL.createObjectURL(newBlob([blob], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }));   
        return imgUrl
    })
}

kml转geojson

getKml(url) {
    fetch(url,{method:'get',responseType: 'blob'}).then(res=>res.blob()).then(blob => {
        const reader = newFileReader();
        reader.readAsText(blob,'utf-8');
        reader.onload = function (e) {
            const xml = newDOMParser().parseFromString(e.target.result,'text/xml')
            const geojson = togeojson.kml(xml, {
                style: true
            })
            return geojson
        }
    })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值