2

I'm using Cropper 3.1.3 and DropzoneJS 5.2.0, two popular JavaScript library to crop images and drop/upload images, respectively.

I will omit a lot of the code that surrounds the UI. At a certain point I select a crop area and I press a "crop" button. The button executes:

$image.cropper(
               'getCroppedCanvas', 
               {fillColor: '#fff'}
              )
              .toBlob(function (blob) {
                        var croppedFile = blob; 
                        croppedFile.lastModifiedDate = new Date();
                        croppedFile.name = fileName;
                        croppedFile.accepted = true;
                        var files = myDropzone.getAcceptedFiles();
                        for (var i = 0; i < files.length; i++) {
                            var file = files[i];
                            if (file.name === fileName) {
                                myDropzone.removeFile(file);
                            }
                        }

                        myDropzone.files.push(croppedFile);
                        myDropzone.emit('addedfile', croppedFile);
                        $cropperModal.modal('hide');
                    });

From this, I expected that the blob (file) is sent to the dropzone and added and at the end the thumbnail is created. But this does not happens. So, how can I enforce the creation of the thumbnail using DropzoneJS?

I have a complete JSFiddle here to reproduce the problem.

JeanValjean
  • 17,172
  • 23
  • 113
  • 157

1 Answers1

2

There may be a problem with the version of DropZone you're using https://gitlab.com/meno/dropzone/issues/56

You can work around it by modifying the event handler for addedfile to generate an objectURL for the preview:

myDropzone.on('addedfile', function(file) {
  if (!cropped) {
    myDropzone.removeFile(file);
    cropper(file);
  } else {
    cropped = false;
    var previewURL = URL.createObjectURL(file);
    var dzPreview = $(file.previewElement).find('img');
    dzPreview.attr("src", previewURL);
  }
});

Updated JSFiddle: https://jsfiddle.net/m02t97fa/

K Scandrett
  • 16,390
  • 4
  • 40
  • 65
  • For completeness I should add that my snippet works only because in `$image.cropper('getCroppedCanvas', {...` it has `cropped = true`, and the cropped version of the image is then added to DropZone via `myDropzone.emit('addedfile', croppedFile);`. This re-triggers the `addedfile` event handler using the cropped version – K Scandrett Nov 11 '17 at 04:40
  • Hello, thanks for the answer. So just changing that ``else`` as you proposed seems to have fixed the issue. Thanks a lot. I'll do more tests and in case award the bounty. – JeanValjean Nov 11 '17 at 09:29