上传图片截图预览控件不显示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 '';
  }

可以显示出来了

原文地址:https://www.cnblogs.com/xiongzaiqiren/p/6889176.html