Vue 之 利用new Blob() 对后端返回文件流 或 base64字符串下载导出文件时不同文件类型的 type 值整理及函数封装调用示例

mimeType类型字符串对应整理以及文件流、base64字符串下载文件函数封装

在 Vue 项目中,经常用 Blob 二进制进行文件下载功能(vue后台返回文件流下载导出函数封装、后台返回base64字符串下载导出函数封装、调用示例),涉及不同后缀名的文件,这里整理一份 Blob 的配置关系对应表,在我们使用Blob做下载功能时 ,根据需要下载的文件类型修改 type 值进行下载即可。

文件后缀名、文件类型、mimeType值对应关系表

后缀名文件类型类型(type)
.xlsMicrosoft Excelapplication/vnd.ms-excel
.xlsxMicrosoft Excel (OpenXML)application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.csvCSVtext/csv
.docMicrosoft Wordapplication/msword
.docxMicrosoft Word (OpenXML)application/vnd.openxmlformats-officedocument.wordprocessingml.document
.pdfPDFapplication/pdf
.pptMicrosoft PowerPointapplication/vnd.ms-powerpoint
.pptxMicrosoft PowerPoint (OpenXML)application/vnd.openxmlformats-officedocument.presentationml.presentation
.png便携式网络图形(PNG)image/png
.gifGIFimage/gif
.jpegJPEG 图片image/jpeg
.jpgJPEG 图片image/jpeg
.mp3MP3 音频audio/mpeg
.aacAAC 音频audio/aac
.html超文本标记语言 (HTML)text/html
.cssCSStext/css
.jsJavaScripttext/javascript
.jsonJSON 格式application/json
.abwAbiWord 文档application/x-abiword
.arc存档文档(多个文件嵌入)application/x-freearc
.aviAVI: 音频视频交错video/x-msvideo
.azw亚马逊Kindle电子书格式application/vnd.amazon.ebook
.bin任何类型的二进制数据application/octet-stream
.bmpWindows OS/2位图图形image/bmp
.bzBZip 存档application/x-bzip
.bz2BZip2 存档application/x-bzip2
.cshC-Shell 脚本application/x-csh
.eotMS嵌入式OpenType字体application/vnd.ms-fontobject
.epub电子出版物(EPUB)application/epub+zip
.htm超文本标记语言 (HTML)text/html
.icoIcon 格式image/vnd.microsoft.icon
.icsiCalendar 格式text/calendar
.jarJava Archive (JAR)application/java-archive
.jsonldJSON-LD 格式application/ld+json
.mid乐器数字接口(MIDI)audio/midi audio/x-midi
.midi乐器数字接口(MIDI)audio/midi audio/x-midi
.mjsJavaScript 模块text/javascript
.mpegMPEG 视频video/mpeg
.mpkg苹果安装程序包application/vnd.apple.installer+xml
.odpOpenDocument演示文档application/vnd.oasis.opendocument.presentation
.odsOpenDocument 电子表格文件application/vnd.oasis.opendocument.spreadsheet
.odtOpenDocument 文本文档application/vnd.oasis.opendocument.text
.ogaOGG 音频audio/ogg
.ogvOGG 视频video/ogg
.ogxOGGapplication/ogg
.otfOpenType 字体font/otf
.rarRAR 存档application/x-rar-compressed
.rtf富文本格式 (RTF)application/rtf
.shBourne shell 脚本application/x-sh
.svg可缩放矢量图形 (SVG)image/svg+xml
.swf小型web格式 (SWF) or Adobe Flash documentapplication/x-shockwave-flash
.tarTape 归档(TAR)application/x-tar
.tif标记图像文件格式 (TIFF)image/tiff
.tiffTagged Image File Format (TIFF)image/tiff
.ttfTrueType 字体font/ttf
.txtTexttext/plain
.vsdMicrosoft Visioapplication/vnd.visio
.wav波形音频格式audio/wav
.webaWEBM 音频audio/webm
.webmWEBM 视频video/webm
.webpWEBP 图片image/webp
.woff网页开放字体格式 (WOFF)font/woff
.woff2网页开放字体格式 (WOFF)font/woff2
.xhtmlXHTMLapplication/xhtml+xml
.xmlXMLapplication/xml(普通用户不可读)、text/xml(普通用户可读)
.xulXULapplication/vnd.mozilla.xul+xml
.zipZIPapplication/zip
.3gp3GPP audio/video 容器video/3gpp、audio/3gpp(不含视频)
.3g23GPP2 audio/video 容器video/3gpp2、audio/3gpp2(不含视频)
.7z7-zipapplication/x-7z-compressed



函数封装

为 此,将 工 作 中 常 用 的 公 共 方 法 封 装 整 理 了 一 份(不定时更新)点击此处查看

  这里可以将这些公共方法全部写在一个 publicMethods.js 文件中,然后在 main.js 文件中引入,并抛给 vue 原型,然后这样的好处就是,不管在哪个 vue 文件中,都能通过 this.xxx.xxx 的方式调用封装的公共方法;

  • publicMethods.js
// 创建一个a标签,并做点击下载事件
function downloadFile(hrefUrl, fileName){
    let a = document.createElement('a')
    a.href = hrefUrl
    a.download = fileName // 下载后文件名
    document.body.appendChild(a)
    a.click() // 点击下载
    document.body.removeChild(a) // 下载完成移除元素
}
// 封装blob对象
function dataURLToBlob(base64Str, mimeTypeStr) {
    let bstr = window.atob(base64Str); // 解码 base-64 编码的字符串,base-64 编码使用方法是 btoa()
    let length = bstr.length;
    let u8arr = new Uint8Array(length); // 创建初始化为0的,包含length个元素的无符号整型数组
    while (length--) {
        u8arr[length] = bstr.charCodeAt(length); // 返回在指定的位置的字符的 Unicode 编码
    }
    return new Blob([u8arr], { type: mimeTypeStr }); // 返回一个blob对象
}

// 后端返回base64公共导出
function downloadFileByBase64(base64Str, mimeTypeStr, fileName){
    let myBlob = dataURLToBlob(base64Str, mimeTypeStr)
    let myUrl = window.URL.createObjectURL(myBlob)
    downloadFile(myUrl, fileName)
}
// 后端返回文件流公共导出
function downloadFileByFileFlow(blobData, mimeTypeStr, fileName) {
    let blob = new Blob([blobData], { type: mimeTypeStr })
    let hrefUrl = window.URL.createObjectURL(blob) // 创建下载的链接
    downloadFile(hrefUrl, fileName);
}
  • main.js
import publicMethod from './utils/publicMethods.js';
Vue.prototype.$public = publicMethod;
  • 相应的vue文件中
// res为后端返回的base64字符串
this.$public.downloadFileByBase64(res, 'application/vnd.ms-excel', '订单明细');
// res为后端返回的文件流
this.$public.downloadFileByFileFlow(res, 'application/vnd.ms-excel', '订单明细');

  
  

  如有不足,望大家多多指点! 谢谢!

  • 24
    点赞
  • 113
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
如果你想在前端接收到后端返回文件名,可以在后端设置一个响应头来指定文件名,然后在前端通过获取响应头来获取文件名。具体操作如下: 后端代码示例(Node.js): ``` const fs = require('fs'); const path = require('path'); const express = require('express'); const app = express(); app.get('/download', function(req, res) { const filePath = path.join(__dirname, 'example.txt'); const fileName = 'example.txt'; const stat = fs.statSync(filePath); res.setHeader('Content-Disposition', 'attachment; filename=' + fileName); res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Length', stat.size); const stream = fs.createReadStream(filePath); stream.pipe(res); }); app.listen(3000, function() { console.log('Server is running on port 3000'); }); ``` 在上面的代码中,我们设置了 `Content-Disposition` 响应头来指定文件名为 example.txt。 前端代码示例Vue.js): ``` downloadFile() { axios({ url: 'http://localhost:3000/download', method: 'GET', responseType: 'blob', }).then((response) => { const contentDisposition = response.headers['content-disposition']; const fileName = contentDisposition.split(';')[1].split('=')[1].replace(/"/g, ''); const blob = new Blob([response.data]); const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); }); }, ``` 在上面的代码中,我们通过 `responseType: 'blob'` 来告诉 axios,我们需要接收一个二进制。然后,我们通过获取响应头中的 `Content-Disposition` 字段来获取文件名,并使用 `new Blob()` 方法创建一个 Blob 对象,再通过创建一个 `<a>` 标签来触发下载操作,并设置 `download` 属性为文件名。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhuangvi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值