base64格式文件下載方法


下載圖片時,接口返回的地址是base64格式的文件數據,因為頁面需要把base64格式的數據轉換為文件,再進行下載:

解決方案:

  下載按鈕:

<el-button type="default" class="btnfoot" @click="downloadFun">下載</el-button>

  下載事件:

  以下方法:downloadFile、base64ToBlob可以直接使用。

  其中,multipleSelection表示所勾選的下載數據列表信息

downloadFun() {
      console.log(this.multipleSelection);
      for (let i = 0; i < this.multipleSelection.length; i++) {
        const param = {
          Command: 'downloadfile',
          FileName: this.multipleSelection[i].FileName
        }
        videoImgDownload(param).then(response => {
          console.log('videoImgDownload');
          console.log(response);
          if (response.StateCode == '200') {
            this.base64Src = response.FileData;
            this.downloadFile(response.FileName, this.base64Src);
          } else {
            this.$notify({title: '異常', message: response.message, type: 'warning', duration: 0});
          }
        });
      }
    },
    downloadFile(fileName, content) {
      const blob = this.base64ToBlob(content); // new Blob([content]);
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;

        //此寫法兼容可火狐瀏覽器
        document.body.appendChild(link);
        const evt = document.createEvent("MouseEvents");
        evt.initEvent("click", false, false);
        link.dispatchEvent(evt);
        document.body.removeChild(link);
      }
    },
    base64ToBlob(code) {
      const parts = code.split(';base64,');
      const contentType = parts[0].split(':')[1];
      const raw = window.atob(parts[1]);
      const rawLength = raw.length;
      const uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    },

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM