Vue uses new Blob() to realize different types of file downloads

        In the actual development process of the Vue project, it is often necessary to download various types, because I am not born in the front end, so I learned online and finally used it in my own project. Please give me more guidance on low-level errors such as code redundancy. I've found that Blob binaries are used more often for file downloads, so that's what I'm going for.

        The following is a corresponding table of Blob configuration relationship. When we use Blob as the download function, just modify the type value according to the file type to be downloaded and download it.

File suffix name, file type, mimeType value correspondence table

suffix         file type type
.xls Microsoft Excel application/vnd.ms-excel
.xlsx Microsoft Excel (OpenXML) application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.csv CSV text/csv
.doc Microsoft Word application/msword
.docx Microsoft Word (OpenXML) application/vnd.openxmlformats-officedocument.wordprocessingml.document
.pdf PDF application/pdf
.ppt Microsoft PowerPoint application/vnd.ms-powerpoint
.pptx Microsoft PowerPoint (OpenXML) application/vnd.openxmlformats-officedocument.presentationml.presentation
.png Portable Network Graphics (PNG) image/png
.gif GIF image/gif
.jpeg jpeg images image/jpeg
.jpg jpeg images image/jpeg
.mp3 MP3 audio audio/mpeg
.aac AAC audio audio/aac
.html Hypertext Markup Language (HTML) text/html
.css CSS text/css
.js JavaScript text/javascript
.json JSON format application/json
abv AbiWord document application/x-abiword
.arc Archive Documentation (multiple files embedded) application/x-freearc
.avi AVI: Audio Video Interleave video/x-msvideo
.azw Amazon Kindle eBook format application/vnd.amazon.ebook
.bin any type of binary data application/octet-stream
.bmp Windows OS/2 bitmap graphics image/bmp
.bz BZip archive application/x-bzip
.bz2 BZip2 archive application/x-bzip2
.csh C-Shell script application/x-csh
.eot MS embedded OpenType fonts application/vnd.ms-fontobject
.epub Electronic Publication (EPUB) application/epub+zip
.htm Hypertext Markup Language (HTML) text/html
.ico Icon format image/vnd.microsoft.icon
.ics iCalendar format text/calendar
.jar Java Archive (JAR) application/java-archive
.jsonld JSON-LD format application/ld+json
.mid Musical Instrument Digital Interface (MIDI) audio/midi audio/x-midi
.midi Musical Instrument Digital Interface (MIDI) audio/midi audio/x-midi
.mjs JavaScript modules text/javascript
.mpeg MPEG video video/mpeg
.mpkg apple installer package application/vnd.apple.installer+xml
.odp OpenDocument presentation document application/vnd.oasis.opendocument.presentation
.ods OpenDocument spreadsheet file application/vnd.oasis.opendocument.spreadsheet
.odt OpenDocument 文本文档 application/vnd.oasis.opendocument.text
.oga OGG 音频 audio/ogg
.ogv OGG 视频 video/ogg
.ogx OGG application/ogg
.otf OpenType 字体 font/otf
.rar RAR 存档 application/x-rar-compressed
.rtf 富文本格式 (RTF) application/rtf
.sh Bourne shell 脚本 application/x-sh
.svg 可缩放矢量图形 (SVG) image/svg+xml
.swf 小型web格式 (SWF) or Adobe Flash document application/x-shockwave-flash
.tar Tape 归档(TAR) application/x-tar
.tif 标记图像文件格式 (TIFF) image/tiff
.tiff Tagged Image File Format (TIFF) image/tiff
.ttf TrueType 字体 font/ttf
.txt Text text/plain
.vsd Microsoft Visio application/vnd.visio
.wav 波形音频格式 audio/wav
.weba WEBM 音频 audio/webm
.webm WEBM 视频 video/webm
.webp WEBP 图片 image/webp
.woff 网页开放字体格式 (WOFF) font/woff
.woff2 网页开放字体格式 (WOFF) font/woff2
.xhtml XHTML application/xhtml+xml
.xml XML application/xml(普通用户不可读)、text/xml(普通用户可
.xul XUL application/vnd.mozilla.xul+xml
.zip ZIP application/zip
.3gp 3GPP audio/video 容器 video/3gpp、audio/3gpp(不含视频)
.3g2 3GPP2 audio/video 容器 video/3gpp2、audio/3gpp2(不含视频)
.7z 7-zip application/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"];进行获取即可。

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

 

Guess you like

Origin blog.csdn.net/m0_64210833/article/details/130202081