首页 > 其他分享 >ajax下载文件(图片/视频/excel)

ajax下载文件(图片/视频/excel)

时间:2023-02-12 19:46:21浏览次数:32  
标签:body 视频 url res excel ajax blob document type

//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(url, 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(url, 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);
}

 

标签:body,视频,url,res,excel,ajax,blob,document,type
From: https://www.cnblogs.com/mengff/p/17114528.html

相关文章