Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting local file drag'n'drop with HTML/JavaScript

There is a HTML textarea. I'm able to catch that event when a local file is dragged and dropped onto the textarea. But how to obtain the name of the dropped file? (To be modified and inserted into the textarea finally.)

The following expressions returns None in that case:

event.dataTransfer.files
event.dataTransfer.getData('text/plain')

I made a short example for Firefox 3 that is my target platform currently.

<script>
function init() {
    document.getElementById('x').addEventListener('drop', onDrop, true)
}
function onDrop(event) {
    var data = event.dataTransfer.getData('text/plain')
    event.preventDefault()
    alert('files: ' + event.dataTransfer.files + ' && data: ' + data + '.')
}
</script>

<body onload='init()'>
<textarea cols=70 rows=20 id='x'></textarea>
like image 413
Pavel Vlasov Avatar asked Jan 07 '10 05:01

Pavel Vlasov


2 Answers

This is a bit late - but I think what you are looking for is this:

event.dataTransfer.files[0].name

You can also get the following properties:

event.dataTransfer.files[0].size
event.dataTransfer.files[0].type

And you can loop thru these files with the following:

var listOfNames='';
for(var i=0,tot=event.dataTransfer.files.length; i<tot; i++){
    listOfNames+=event.dataTransfer.files[i].name + '\r\n';
}

Btw - if you are using jQuery then the dataTransfer object can be found here:

event.originalEvent.dataTransfer.files[0].name
like image 196
Jimmery Avatar answered Nov 04 '22 02:11

Jimmery


Don't know if it's still relevant, but I faced the same problem. Here's how I solved it:

  1. Create a normal upload form with a single input field (type="file")
  2. Add this HTML attribute to the input field:

    dropzone="copy file:image/png file:image/jpg file:image/jpeg"

  3. Set JQuery listener or whatever to catch the "drop"-event on the input field

When you drag & drop a local image on the input field, the "value" attribute is filled automatically and you can process it like any other HTML form.

I also wrapped the form into another HTML element (div), set the size of the div and set overflow:hidden via CSS - this way, you can get rid of the "browse" button. It's not nice, but it works. I also used the AjaxForm plugin to upload the image in the background - works very nice.

like image 36
Jan Petzold Avatar answered Nov 04 '22 03:11

Jan Petzold