js中下载二进制流格式的文件

581 阅读1分钟

axios读取blob文件

axios({
    method: 'GET',
    url: '/api/download',
    params: {
        reportRuleId: row.reportRuleId
    },
    responseType: 'blob'
}).then(response => {
    if (response.data.type === 'application/octet-stream') {
        // 获取http头部的文件名信息,若无需重命名文件,将下面这行删去
        const fileName = response.headers['content-disposition'].split('=')[1]
        /* 兼容ie内核,360浏览器的兼容模式 */
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            const blob = new Blob([response.data], { type: 'application/zip' })
            window.navigator.msSaveOrOpenBlob(blob, fileName)
        } else {
            /* 火狐谷歌的文件下载方式 */
            const blob = new Blob([response.data], { type: 'application/zip' })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a') // 创建a标签
            link.href = url
            link.download = fileName // 文件重命名,若无需重命名,将该行删去
            link.click()
            URL.revokeObjectURL(url) // 释放内存
        }
        resolve(response)
    } else {
        const reader = new FileReader()
        reader.onload = function (event) {
            const msg = JSON.parse(reader.result).data
            _this.$errorMsg(message) // 将错误信息显示出来
        }
        reader.readAsText(response.data)
    }
}).catch(error => _this.$errorMsg(error))

fetch读取二进制文件

fetch(url, newOptions)
    .then(res => res.blob())
    .then(data => {
        let downloadURL = window.URL.createObjectURL(data);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = downloadURL;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(downloadURL);
    });

读取Blob文件的两种方式

  • 从Blob中读取内容的方法是使用 FileReader。以下代码将 Blob 的内容作为类型数组读取:
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.addEventListener("loadend", function(result) {
   // reader.result 包含被转化为类型数组 typed array 的 blob
});

  • 使用Response对象。下述代码将Blob中的内容读取为文本:
var text = await (new Response(blob)).text();