1. 程式人生 > 其它 >遠端圖片資源跨域問題(vue頁面匯出pdf時,圖片不能顯示)

遠端圖片資源跨域問題(vue頁面匯出pdf時,圖片不能顯示)

方案一:(實測無效,仍會報跨域問題,不推薦)

<!-- 新增crossorigin=“anonymous”屬性 同時 後端配置該圖片地址的跨域-->
<img crossorigin="anonymous" :src="imgSrc ? imgSrc : ''"/>

結論:

後端是否配置跨域 加crossorigin屬性 不加crossorigin屬性
可以正常載入,準確捕獲錯誤 可以正常載入,無法準確捕獲錯誤
無法正常載入 可以正常載入,無法準確捕獲錯誤

方案二:(base64轉碼,實測有效,推薦)

<img :src="imgSrc ? imgSrc : ''"/>
// imgUrl 遠端圖片資源地址
    getBase64(imgUrl) {
      let that = this
        window.URL = window.URL || window.webkitURL;
        var xhr = new XMLHttpRequest();
        xhr.open("get", imgUrl, true);
        xhr.responseType = "blob";
        xhr.onload = function () {
          if (this.status == 200) {
            var blob = this.response;
            console.log("blob", blob)
            let oFileReader = new FileReader();
            oFileReader.onloadend = function (e) {
              that.imgSrc = e.target.result
            };
            oFileReader.readAsDataURL(blob);
          }
        }
        xhr.send();
      },