当前位置:首页 » 《随便一记》 » 正文

【前端】Vue之使用new Blob() 实现不同类型的文件下载

26 人参与  2024年02月07日 10:56  分类 : 《随便一记》  评论

点击全文阅读


        在 Vue 项目实际开发过程中,经常需要对各种各样的类型进行下载,因为我不是前端出生,就自己在网上学习最后使用到自己的项目当中,代码冗余等低级错误还请多多指导。我发现用 Blob 二进制进行文件下载的比较多,我就采用了这一方式。

        下面是一份 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

代码实现

HTML

文件下载按钮,data中定义的我就没有写了哈,自己定义就好了。

<el-button icon="el-icon-search" v-model="formDetail.downloadAddress" :style="{width: '60%'}" class="underline"                        @click="downloadExample(formDetail.assetNo,formDetail.downloadAddress)">点击下载                </el-button>

JavaScript

        项目中后端返回的是文件上传成功生成的一个字符串,为了保证可以下载所有文件,需要对后缀进行截取进行判断然后取不同的new Blob,这里new Blob中后端直接返回的是文件流,所以直接用res进行获取

downloadExample(assetNo,downloadAddress){       axios({            method: "get",            url: '/dev-api/directory/io/exportdemo?assetNo=' + assetNo + '&fileNo=' + downloadAddress,            data: "",            responseType: "blob", // 指定响应类型为二进制数据          }).then((res) => {        // 下载格式为zip { type: "application/zip" }        let suffix = downloadAddress.substring(downloadAddress.lastIndexOf("."))        if (suffix=='.xls'){          let blob = new Blob([res], {type: "application/vnd.ms-excel"});          this.ways(blob,suffix);        }else if (suffix=='.xlsx'){          let blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});          this.ways(blob,suffix);        }else if (suffix=='.doc'){          let blob = new Blob([res], {type: "application/msword"});          this.ways(blob,suffix);        }else if (suffix=='.docx'){          let blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});          this.ways(blob,suffix);        }else if (suffix=='.png'){          let blob = new Blob([res], {type: "pplication/pdf"});          this.ways(blob,suffix);        }else if (suffix=='.ppt'){          let blob = new Blob([res], {type: "application/vnd.ms-powerpoint"});          this.ways(blob,suffix);        }else if (suffix=='.png'){          let blob = new Blob([res], {type: "image/png"});          this.ways(blob)        }else if (suffix=='.pptx'){          let blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"});          this.ways(blob,suffix);        }else if (suffix=='.jpeg'){          let blob = new Blob([res], {type: "image/jpeg"});          this.ways(blob,suffix);        }else if (suffix=='.zip'){          let blob = new Blob([res], {type: "application/zip"});          this.ways(blob,suffix);        }else if (suffix=='.7z'){          let blob = new Blob([res], {type: "application/x-7z-compressed"});          this.ways(blob,suffix);        }else if (suffix=='tar'){          let blob = new Blob([res], {type: "application/x-tar"});          this.ways(blob,suffix);        }else if (suffix=='.7z'){          let blob = new Blob([res], {type: "application/x-7z-compressed"});          this.ways(blob,suffix);        }      })    },       ways(blob, suffix,res) {      let elink = document.createElement("a");   // 创建一个<a>标签      elink.style.display = "none";                       // 隐藏标签      elink.href = window.URL.createObjectURL(blob);      // 配置href      // 获取后端返回的响应头中的名称      let filename = res.headers["content-disposition"];       let newFilename = filename.split(';')[1].split('=')[1];      //自定义名称      // let newFilename = "样例文件" + new Date().getTime() + suffix; //自定义名字      // let newFilename = decodeURIComponent(res.headers["content-disposition"].split(';')[1].split('=')[1])      newFilename = decodeURIComponent(newFilename);      elink.download = newFilename;      elink.click();      URL.revokeObjectURL(elink.href);   // 释放URL 对象(弹出框进行下载)      document.body.removeChild(elink);  // 移除<a>标签    },

拓展:如果想获取响应头中的信息比如

直接使用

res.headers["XXX"];进行获取即可。

这样就可以实现各种类型的文件的下载了,很巴适。


点击全文阅读


本文链接:http://m.zhangshiyu.com/post/67678.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1