<返回更多

JavaScript前端通过文件流下载文件

2023-04-03  今日头条  RemoveS
加入收藏

文件流通过接口获取后调用以下方法模拟下载

/**
 * @description 文件流下载方法
 * @param {文件流} blob
 * @param {文件名} fileName
 * @param {文件后缀名} fileType
 */
downloadFile: function(blob, fileName, fileType) {
    var _fileType = fileType && fileType.toUpperCase();//转成大写
    var type = this.MIMITypes[_fileType] || "Application/octet-stream";//通过下方常用MIMITypes获得type
    var url = URL.createObjectURL(new Blob([blob],{
        type: type
    }));//生成url对象
    var a = document.createElement("a");//创建a标签
    a.style.display = "none";//隐藏a
    a.href = url;//赋值a标签的href
    a.download = fileName;//设置下载的文件名
    document.body.appendChild(a);//把a标签添加到页面上
    a.click();//模拟点击
    document.body.removeChild(a);//移除a标签
    URL.revokeObjectURL(url);//释放URL.createObjectURL创建的对象URL
}
//常用MIMITypes
MIMITypes:{
    "TXT": "text/plain",
    "css": "text/css",
    "JPEG": "image/jpeg",
    "JPG": "image/jpeg",
    "PNG": "image/png",
    "GIF": "image/gif",
    "WEBP": "image/webp",
    "SVG": "image/svg+xml",
    "TIFF": "image/tiff",
    "MPEG": "video/mpeg",
    "MP4": "video/mp4",
    "AVI": "video/x-msvideo",
    "OGG": "video/ogg",
    "MP3": "audio/mpeg",
    "PDF": "application/pdf",
    "PPT": "application/vnd.ms-powerpoint",
    "PPTX": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    "XML": "application/xml",
    "CSV": "application/csv",
    "ZIP": "application/zip",
    "7Z": "application/x-7z-compressed",
    "GZIP": "application/gzip",
    "XLS": "application/vnd.ms-Excel",
    "XLSX": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "DOC": "application/msword",
    "DOCX": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "": "application/octet-stream"
}
声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>