Uploading an image cropped using a cropper.js plugin

前端 未结 3 1210
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-14 17:01

I have used cropper.js plugin in my application to crop images. I am able to crop the images. Now I am trying to upload the images instead of downloading them. I have updated th

相关标签:
3条回答
  • 2021-02-14 17:40

    Though this question was asked long back, still I am sharing a link to the solution I just posted in context to someone else's problem.

    I hope it will help someone found on this page. ( Like I landed and found no solution ) Crop image using Cropper.js, then upload (or display) the cropped image.

    0 讨论(0)
  • 2021-02-14 17:44

    In you code above, remember Canvas function toBlob accepts 3 params (as per Mozilla docs):

    • callback
    • mimeType e.g. image/jpg
    • quality e.g 90

    So in your function you can include the mimeType and quality options. Also in the append line include a thirds parameter for filename (with same extension)

    canvas.toBlob(function (blob) {
      var formData = new FormData();
      
      /* Add blob and file name */
      formData.append('croppedImage', blob, 'file.jpg');
    
      $.ajax('/path/to/upload', {
        method: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function () {
          console.log('Upload success');
        },
        error: function () {
          console.log('Upload error');
        }
      });
    
    /* This is the important part */
    }, 'image/jpeg', 0.9);
    
    0 讨论(0)
  • 2021-02-14 17:53

    github.com/fengyuanchen/cropperj Api Doc for Server Upload as formData and Image src tag definition.

    and watch out the below paragraph of getCroppedCanvas():

    After then, you can display the canvas as an image directly, or use HTMLCanvasElement.toDataURL to get a Data URL, or use HTMLCanvasElement.toBlob to get a blob and upload it to server with FormData if the browser supports these APIs.

    0 讨论(0)
提交回复
热议问题