簡述先後端分離的狀況下,Vue實現點擊圖片下載到本地(並實現IE11瀏覽器的兼容)

一、簡述前端

   在先後端分離的項目中涉及跨域問題,一般都會使用token進行驗證。最近在先後端分離的項目中在一個問題上搞了好久,就是之前下載附件或者導出數據爲文件的時候,
在之前的那些項目前端能夠直接用
window.location.href='後端url'
window.open(url)或者其餘的方式,
可是在先後端分離中這種方式不能把token也一塊兒傳到後端
進行請求,致使權限不夠訪問不了後端。

二、基本使用後端

  • Html代碼
    <el-button type="primary" @click="downLoad(url)">下載圖片</el-button>
  • Script代碼
    • data數據
      url : '文件下載地址'
    • methods方法
       /**
         * [getBlob 獲取二進制流]
         * @param  {[String]}     url     [url]
         * @param  {[Blob]}               [文件二進制]
         */
        getBlob(url) {
          return new Promise(resolve => {
            const xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.responseType = "blob";
            xhr.onload = () => {
              if (xhr.status === 200) {
                resolve(xhr.response);
              }
            };
            xhr.send();
          });
        },
        /**
          * [saveAs 下載保存文件]
          * @param  {[type]} fileUrl [文件地址]
          */
          saveAs(fileUrl) {
            if (window.navigator.msSaveOrOpenBlob) {
              // 兼容IE11 發如今微軟在ie10 和ie11中有兩個特有的方法:window.navigator.msSaveBlob和window.navigator.msSaveOrOpenBlob 方法,
      //這兩個方法的區別在於,前者只有保存,後者有保存和打開兩個選項,按我的喜愛使用就行
              this.getBlob(fileUrl).then(blob => {
                navigator.msSaveBlob(
                  blob,
                  decodeURIComponent(
                    fileUrl
                      .split("?")[1]
                      .split("&")[0]
                      .split("=")[1]
                  )
                );
              });
            } else {
              const iframe = document.createElement("iframe");
              iframe.style.display = "none"; // 防止影響頁面
              iframe.style.height = 0; // 防止影響頁面
              iframe.src = fileUrl;
              document.body.appendChild(iframe); // 這一行必須,iframe掛在到dom樹上纔會發請求
              // 5分鐘以後刪除(onload方法對於下載連接不起做用,就先摳腳一下吧)
              setTimeout(() => {
                iframe.remove();
              }, 5 * 60 * 1000);
            }
          },
          downLoad(url) {
            this.saveAs(url);
          }
      View Code

三、遇到的問題跨域

  • 下載的時候彈出警告框,不影響

相關文章
相關標籤/搜索