2

I am using Dropzone plugin for multiple files drag n drop functionality. Drag n drop works fine when I am uploading pictures from my laptop / desktop.

My question is - how can I drag n drop images into dropzone from same page. Lets say I have a dropzone div and I am having another div having multiple images. I want to drag n drop those images into dropzone.

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Raj Sf
  • 1,408
  • 1
  • 17
  • 26

1 Answers1

2
this.on("drop", function(event) {
  var imageUrl = event.dataTransfer.getData('URL');
  var fileName = imageUrl.split('/').pop();

  // set the effectAllowed for the drag item
  event.dataTransfer.effectAllowed = 'copy';

  function getDataUri(url, callback) {
    var image = new Image();

    image.onload = function() {
      var canvas = document.createElement('canvas');
      canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
      canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size

      canvas.getContext('2d').drawImage(this, 0, 0);

      // Get raw image data
      // callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));

      // ... or get as Data URI
      callback(canvas.toDataURL('image/jpeg'));
    };

    image.setAttribute('crossOrigin', 'anonymous');
    image.src = url;
  }

  function dataURItoBlob(dataURI) {
    var byteString,
        mimestring

    if (dataURI.split(',')[0].indexOf('base64') !== -1) {
      byteString = atob(dataURI.split(',')[1])
    } else {
      byteString = decodeURI(dataURI.split(',')[1])
    }

    mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

    var content = new Array();
    for (var i = 0; i < byteString.length; i++) {
      content[i] = byteString.charCodeAt(i)
    }

    return new Blob([new Uint8Array(content)], {
      type: mimestring
    });
  }

  getDataUri(imageUrl, function(dataUri) {
    var blob = dataURItoBlob(dataUri);
    blob.name = fileName;
    myDropzone.addFile(blob);
  });
});

http://codepen.io/BartSitek/pen/ZeMGjV

Here’s my solution to the problem. Data conversion functions were found on the internet. 
And here’s a little explanation of what’s really happening:

  • During “drop” event grab the URL of the image you are dragging

  • Convert that URL to Data URI format

  • Convert Data URI to Blob
  • Add Blob to Dropzone form
B Λ R T
  • 174
  • 1
  • 2
  • 8
  • 1
    This only works with images on the same domain. It requires the server to have setup the correct CORS headers. (Try draging an image from an other tab inside the dropzone). If the server hasn't setup the CORS headers, it won't ever reach the img.onload function. – Alexandre May 20 '17 at 03:29
  • 1
    is there a way to do this drag and drop programmatically, on some event? – James Cazzetta Jul 01 '21 at 13:04