ajax下载blob(图片/视频/excel/txt)

复制代码
//fetch下载文件流
function download(url){
    fetch(url).then(res => {
        return res.blob();
        //return res.arrayBuffer();
    }).then(res => {
        let type = "video/*"  // 资源类型
        /* 常见资源类型
          1.excel: type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          2.图片: type = "image/*"
          3.视频: type = "video/*"
          4.音频: type = "audio/*"
        */
        // blob或arrayBuffer,二者转换为blob的方式一样
        let blob = new Blob([res], {type: type});
        // 获取的blob根据实际业务场景应用下载,或转化成其他格式的资源
        downloadBlob(blob);
    })
}

// axios下载
function download(url){
    axios.post(url,data,{responseType:'blob'}).then(res => {
        const blob = new Blob([res.data]);
        downloadBlob(blob);
    })
}

function downloadBlob(blob, fileName){
    const a = document.createElement('a');
    a.download = fileName;
    a.style.display = 'none';
    a.href = URL.createObjectURL(blob);
    document.body.appendChild(a);
    a.click();
    URL.revokeObjectURL(a.href);
    document.body.removeChild(a);
}

function downloadTxt(fileContent, fileName){
    const a = document.createElement('a');
    a.download = fileName;
    a.style.display = 'none';
    a.href = 'data:text/paint;utf-8,' + fileContent;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
复制代码

 

posted @   全玉  阅读(689)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示