Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the file URL from ondrop event in javascript

I'm running the following code for an uploader I'm making.

holder.ondrop = function (e) {
    e.preventDefault();
    console.log(e);
}

I want the user to be able to drag a file from the desktop onto the web browser, and then I want to capture it's location, so that I can manually upload it (Don't want to do the uploading through javascript) My question is though, how do I get the clients location of the file from the event, so that I can put it in a <input type="file"> ?

Thanks.

like image 636
user1020317 Avatar asked Jul 19 '12 10:07

user1020317


2 Answers

Here is an example of mozilla using the dataTransfer object of the event to get a list of files dragged

EXAMPLE

My example:

holder.ondrop = function (e) {
    e.preventDefault();
    if(e.dataTransfer && e.dataTransfer.files.length != 0){
        var files = e.dataTransfer.files //Array of filenames
        files[0]; //the first file in the list

        // code to place file name in field goes here...

    }else{
        // browser doesn't support drag and drop.
    }

    console.log(e);
}

use the mozilla example because its more comprehensive than I've provided.

like image 103
Dpolehonski Avatar answered Nov 04 '22 14:11

Dpolehonski


The input file field can be treated as a normal input field and its value can be fetched as follows.

<input id="inputid" type="file" dropzone="..."> 

holder.ondrop = function (e) {
    e.preventDefault();
    var path = $('#inputid').val();
    //split the string at the lastIndexOf '/' to get filename 
    console.log(e);
}
like image 40
Anirudh Ramanathan Avatar answered Nov 04 '22 15:11

Anirudh Ramanathan