Skip to content

downloadBlobFile

下载接口返回的二进制流

配置项

参数类型是否必选默认值参数描述
blobDatablob-待处理的二进制数据
fileNamestring-文件名称
typestring-文件类型

返回值

类型描述
void-

示例

downloadBlobFile(blobData, '测试', 'docx')

源码

js
export function downloadBlobFile(blobData, fileName, type) {
    let fileTypeMime = ''; // 文件 mime 类型
    const fileTypeMimeMap = {
        'png': 'image/png',
        'doc': 'application/msword',
        'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'jpg': 'image/jpeg',
        'gif': 'image/gif',
        'svg': 'image/svg+xml',
        'tif': 'image/tiff',
        'txt': 'image/plain',
        'ppt': 'application/vnd.ms-powerpoint',
        'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'xls': 'application/vnd.ms-excel',
        'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'zip': 'application/zip',
        '7z': 'application/x-7z-compressed',
    }
    fileTypeMime = fileTypeMimeMap[type]
    let blob = window.URL.createObjectURL(new Blob([blobData], {'type': fileTypeMime}));
    let link = document.createElement('a');
    link.style.display = 'none';
    link.href = blob;
    if (fileName) {
        link.setAttribute('download', fileName + '.' + type)
    }
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) //下载完成移除元素
    window.URL.revokeObjectURL(blob) //释放掉 blob 对象
}