axios文件流下载示例

Posted by zjh on September 16, 2020

注意事项

jquery的ajax是不支持blob形式的,所以要么自己封装jq的ajax,要么用原生的xhr发ajax,要么用axios,个人推荐用axios,方便快捷

源码

 axios({
            url: "file/fileoutput?ids="+id,
            method: "GET",
            responseType: 'blob'
        }).then(response => {
        var prefix = response.headers["content-disposition"];
        var fileName = prefix.substr(prefix.indexOf("=")+1,prefix.length-prefix.indexOf("=")+1)
        var a = document.createElement("a");
        var blob =new Blob([response.data])
        a.setAttribute("download",fileName)
        a.setAttribute("href",window.URL.createObjectURL(blob))
        a.setAttribute("target","_blank");
        a.click()
    })
    .catch((error) => {
            alert("导出失败,因为:"+error);

    })