上傳圖片截圖預覽控件不顯示cropper.js 跨域問題


上傳圖片到圖片服務器,因為域名不同,多以會有跨域問題。

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://img.xxx.com' is therefore not allowed access.

 

照看代碼發現,cropper.js里面對圖片的引用路徑做了判斷,給img標簽添加了 crossorigin="anonymous"(匿名跨域屬性)。

並且用了XMLHttpRequest 的get請求去訪問img的引用路徑,這樣確實訪問不到。需要在圖片服務器,或者返回的請求頭添加 Access-Control-Allow-Origin:*,或Access-Control-Allow-Origin:請求來源域名。

 

有一種簡單快速的解決辦法,就是直接去掉cropper.js里面跨域屬性,因為默認情況下圖片跨域也是可以顯示的。

對於低版本的cropper.js可以這樣:

    this.$clone = $clone = $('<img>');

    $clone.one('load', $.proxy(function () {
      var naturalWidth = $clone.prop('naturalWidth') || $clone.width(),
          naturalHeight = $clone.prop('naturalHeight') || $clone.height();

      this.image = {
        naturalWidth: naturalWidth,
        naturalHeight: naturalHeight,
        aspectRatio: naturalWidth / naturalHeight,
        rotate: 0
      };

      this.url = url;
      this.ready = true;
      this.build();
    }, this)).one('error', function () {
      $clone.remove();
    }).attr({
//      crossOrigin: crossOrigin, // "crossOrigin" must before "src" (#271)
      src: bustCacheUrl || url
    });

注釋掉那行crossOrigin就好了。

 

對於高版本(我用的Cropper v2.3.4)因為代碼調整了,找到 function getCrossOrigin(crossOrigin),將里面返回跨域代碼的那行注釋掉,返回空字符串就好了。

我是這樣改的:

  function getCrossOrigin(crossOrigin) {
      //return crossOrigin ? ' crossOrigin="' + crossOrigin + '"' : '';
      return '';
  }

可以顯示出來了


免責聲明!

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



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