aimme
aimme

Reputation: 6773

how to detect when the user drop an image inside browser current tab viewport?

i want to know how to do the drag and drop image upload.the thing i don't understand is that how to let server know when a user drops an image inside a certain div or to body for uploading?is that supported in all common browsers ie,ff,chrome,safari. thank you :)

Upvotes: 2

Views: 4588

Answers (2)

Robyflc
Robyflc

Reputation: 1209

I'm using Pupload for it. I don't have to worry about how to implement this drag and drop behavior and it gracefully degrades if the browser isn't html 5 compatible.

Upvotes: 2

ShadowScripter
ShadowScripter

Reputation: 7369

I can tell you haven't done much research.

Short answer is, no. There is no method that is supported in all major browsers that will detect when a user drops an image inside the client window.

Also, as Rajat Saxena pointed out in the comments, you'd have to inform the server of a file drop by sending an ajax request on the drop event.


HTML5

Here's drag and drop from desktop to browser using HTML5 and javascript

<div id="drop_zone">Drop files here</div>
<output id="list"></output>

<script>
  function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    var files = evt.dataTransfer.files; // FileList object.

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
      output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                  f.size, ' bytes, last modified: ',
                  f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                  '</li>');
    }
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
  }

  function handleDragOver(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
  }

  // Setup the dnd listeners.
  var dropZone = document.getElementById('drop_zone');
  dropZone.addEventListener('dragover', handleDragOver, false);
  dropZone.addEventListener('drop', handleFileSelect, false);
</script>

JQuery

Here's a drag and drop from desktop to browser using JQuery (Firefox and Chrome)

function ignoreDrag(e) {
  e.originalEvent.stopPropagation();
  e.originalEvent.preventDefault();
}

$('#target')
    .bind('dragenter', ignoreDrag)
    .bind('dragover', ignoreDrag);
    .bind('drop', drop);

function drop(e) {
  ignoreDrag(e);
  var dt = e.originalEvent.dataTransfer;
  var files = dt.files;

  if(dt.files.length > 0){
    var file = dt.files[0];
    alert(file.name);
  }
}

Other related links to plugins (not tested) and questions

Upvotes: 5

Related Questions