使用CropperJS保存裁剪后的图像时,无法读取未定义的属性toBlob

时间:2018-09-25 11:15:22

标签: javascript html ajax cropper cropperjs

我有一个代码,可以通过ajax将裁剪的图像发送到我的服务器,如下所示:

function saveCrop(){
var img = document.querySelector("#banner_image_preview");
var cropper = new Cropper(img);

cropper.getCroppedCanvas().toBlob((blob) => {
    const formData = new FormData();

    formData.append('croppedImage', blob);

    $.ajax('include/product_misc.php', {
      method: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success(result) {
        console.log('Upload success');
        console.log(result);
      },
      error() {
        console.log('Upload error');
      },
    });
  });
}

我的html是这样的:

<!-- Modal -->
<div id="myModal" data-modal-id="cropImage" class="modal">
  <div class="modal-content">
      <img class="" id="banner_image_preview" src="img/banner.jpeg">  
  </div>
  <div class="modal-footer" style="border: none !important;" id="alert_footer">
        <center style="float: left;display: block;width: 100%;">
            <button id="alert-btn" class="btn btn-primary" onclick="saveCrop()">
                Save
            </button>
        </center>
    </div>
</div>

我不断收到此错误Uncaught TypeError: Cannot read property 'toBlob' of null

我尝试了从https://fengyuanchen.github.io/cropperjs处的CropperJS github页面将裁剪后的图像上传到服务器的其他方法。

请协助。

1 个答案:

答案 0 :(得分:0)

我认为您需要做的是window.saveCrop = function(),而不是function saveCrop()

`window.saveCrop = function() {

var img = document.querySelector("#banner_image_preview");
var cropper = new Cropper(img);
cropper.getCroppedCanvas().toBlob((blob) => {
const formData = new FormData();`

formData.append('croppedImage', blob);

$.ajax('include/product_misc.php', {
  method: "POST",
  data: formData,
  processData: false,
  contentType: false,
  success(result) {
    console.log('Upload success');
    console.log(result);
  },
  error() {
    console.log('Upload error');
     },
   });
  });
 }`