Search code examples
javascriptcloudinary

I can't trigger a preview when dropping an image into an input field


I have a drop box to upload images to Cloudinary, which works fine, but I can't trigger a preview function when the images are dropped.

This is the HTML code:

<div class="card text-muted">
    <label id="upload" for="dropboxInput" class="card-block text-muted">
       <input type="file" name="file" data-url="CLOUDINARY_URL"
              data-form-data="{CLOUDINARY STUFF}" 
              data-cloudinary-field="file" class="cloudinary-fileupload"
              multiple="multiple" style="display:none" id="dropboxInput">
  </label>                        
</div>

This is the code to trigger the function, which works fine when selecting the images after clicking the drop box:

var dropboxInput = document.getElementById("dropboxInput");
dropboxInput.onchange = function(){readURL(this)};

I have tried this, but it seems that is not getting the dropboxInput.value. The images, once dropped are uploaded:

var dropbox = document.getElementById("dropbox");
dropbox.ondrop = function(){
    readURL(dropboxInput);
};

This is the preview function, which handles the preview:

function readURL(input){
   if(input.files){

       for (i = 0; i < input.files.length; i++) {
           var reader = new FileReader();

           reader.onload = function(event) {
                 $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(preview);
           }
        reader.readAsDataURL(input.files[i]);
        }
   }    
}

In the input field CLOUDINARY STUFF is this:

<input type="file" name="file" data-url="https://api.cloudinary.com/v1_1/MYACCOUNT/auto/upload" 
data-form-data="{&quot;eager&quot;:&quot;c_limit,h_768,w_1024&quot;,&quot;signature&quot;:&quot;1f5c7426f428ebd02bb45180767fd920716cc59e&quot;,&quot;api_key&quot;:&quot;185516472314647&quot;,&quot;eager_async&quot;:true,&quot;callback&quot;:&quot;/cloudinary_cors.html&quot;,&quot;tags&quot;:&quot;Punta de Vistalegre,2&quot;,&quot;use_filename&quot;:true,&quot;timestamp&quot;:&quot;1527959323&quot;}" 
data-cloudinary-field="file" class="cloudinary-fileupload"
multiple="multiple" style="display:none" id="dropboxInput">

When the images are droped, I don't find the way to pass them to the readURL() function.

Thanks in advance for any help.


Solution

  • The solution was into the cloudinary-fileupload function, which has the drop option, that handles the dropped files. The input field is generated programmatically with this Java code:

     String html = cloudinary.uploader().imageUploadTag("file", options, htmlOptions);
    

    And that's the implementation of the drop option:

    $(".cloudinary-fileupload").cloudinary_fileupload({
       ...
       drop: function(e, data){
    
             readURL(data);
    
       },
       ...