views:

580

answers:

4

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>
A: 

You can not do it with Javascript because of security reasons. Javascript VM has no direct access to OS file system. You can only drag and drop text.

alemjerus
But it is not an usual direct access: a user drops file by her own wish. And an application needs just a file name, not more. What's wrong here?For example the following visual editor is *able* to obtain dropped file's name (you'll need to be logged in unfortunately):http://www.livejournal.com/update.bml and it's made of HTML still.
Pavel Vlasov
A: 

Alemjerus is correct, you don't have access to what you're looking for.

The behavior you mentioned in reply to his comment is the default behavior of certain browsers. For instance, with the stackoverflow textarea for this entry, if I use Safari and drag a file into it, it places the file's path into the textarea. With firefox 3.5, on the other hand, it attempts to open the file with the browser.

Basically, the "drag and drop" functionality you're attempting to implement is something thats handled by the browser and OS on the client machine -- you can't use Javascript for this purpose.

Skone
I know about existance of security in JS. But you and alemjerus are wrong in this particular case.Install Firefox 3.6 and run that pure html/js example:https://developer.mozilla.org/En/DragDrop/DataTransfer#ExampleAnd you will be able to access not only file name but its content ever.The single thing I can't dig out still is how to obtain the *full* file path...
Pavel Vlasov
A: 

Hi Pavel,

as far as I know, you need to obtain an instance of nsIFile in order to get the file path (the File class does not offer this feature).
This MDC page explains how to do this: https://developer.mozilla.org/En/DragDrop/Recommended_Drag_Types#file.
Note that although not listed in the previous link, obtaining an nsIFile instance requires privileges escalation (cf. my answer to http://stackoverflow.com/questions/1067947/can-i-drag-files-from-the-desktop-to-a-drop-area-in-firefox-3-5-and-initiate-an-u show how to do this).

ggrussenmeyer