Khurram Ijaz
Khurram Ijaz

Reputation: 1864

how to get file names from input type file in html 5 using javascript or jquery

below is my simple code using HTML 5 multiple file upload. All i need is to grab all the file names not the paths below is simple javascript code

  function getFileNames()
        {
            var path = $('#files').val();
            console.log(' path = ' + path);
        }

and html form is as

<form action='server.php' method='post' enctype='multipart/form-data' target="iframe">
                <input id="files" name='files[]' type='file' multiple>
                <input type='button' onclick="getFileNames()">
</form>

when i press the button the console output is as

path = Chrysanthemum.jpg

which is the first name of the file and i want the remaining names , any suggestions , comments are appreciated. thanks.

Upvotes: 2

Views: 9177

Answers (3)

user47900
user47900

Reputation: 647

    function getFileNames()
    {
       var files = document.getElementById("files").files;         
    for (var i = 0, f; f = files[i]; i++) {
          console.log(' name= ' + f.name);
alert(' path = ' + f.name);
        }
    }

Upvotes: 1

dku.rajkumar
dku.rajkumar

Reputation: 18568

well so here i am with the solution after lot of research, in case of input type file the value is stored in array as files with key name.

var files = $('input#files')[0].files;
var names = "";
$.each(files,function(i, file){
    names += file.name + " ";
});
alert(names);

fiddle : http://jsfiddle.net/raj_er04/nze2B/1/

pure javascript

function getFileNames(){
    var files = document.getElementById("files").files;
    var names = "";
    for(var i = 0; i < files.length; i++)
        names += files[i].name + " ";
    alert(names);
}

fiddle : http://jsfiddle.net/raj_er04/nze2B/2/

Upvotes: 6

esqew
esqew

Reputation: 44698

Instead of

var path = $('#files').val();

loop through the array, use

var names = "";
var path = $('#files').each(function(i, el) {
    names = names + el.val() + ",";
});

Upvotes: -1

Related Questions