1

我有一个代码可以通过 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 页面将裁剪图像上传到服务器的其他方法。

请协助。

4

1 回答 1

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');
     },
   });
  });
 }`
于 2020-08-25T19:35:17.900 回答