Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file name on drag and drop FileReader

Hi I am using native HTML5 drag and drop to upload files to the server. I want to get the name of the file being uploaded from the local system. I am unable to get the name of the file being dropped in the drop zone. Below is the code i have tried. Any help would be appreciated

var reader = new FileReader();
    reader.onload = function (event) {
        var childrenDivs = document.getElementById("holder").children
        var temp    
        if(childrenDivs.length > 0){

            var lastDiv = childrenDivs[childrenDivs.length - 1]
            temp = parseInt(lastDiv.id.split("_")[1]) + 1
        }else{

            temp = 1
        }
      var imageDiv = document.createElement('div')
      imageDiv.id = "uploadedImage_"+temp
      var image = new Image();
      image.src = event.target.result;
      console.log(event.target.fileName)

instead of console.log(event.target.fileName) i have also tried console.log(event.target.files[0].name) and console.log(event.dataTrasfer.files[0]). Could anyone please help me out here.

like image 205
Apoorv Avatar asked Oct 26 '16 16:10

Apoorv


1 Answers

Where are you calling reader.readAs... method?

AFAIK, the proper place to get the filename would be where you register the drop event of a dom element.

element.ondrop = function(e) {
    e.preventDefault();

    var reader = new FileReader();
    reader.onload = function (event) {
        ....
    }

    var file = e.dataTransfer.files[0];
    // can get the name of the file with file.name
    console.log(file.name);
    reader.readAsBinaryString(file);

}
like image 185
tafa Avatar answered Sep 23 '22 00:09

tafa