How to get the filename from input type=file html element using JavaScript or JQuery?

In Google Chrome browser, i have tried several way + following and none is giving me the value of the file name which was attached, after validation i will submit the file. But always its undefined or val() does not found..

How to resolve it?

console.log($("input[name='attachment[]']"));
/* Output:
[
<input type=?"file" name=?"attachment[]?" id=?"attachment">?
, 
<input type=?"file" name=?"attachment[]?" id=?"attachment">?
, 
<input type=?"file" name=?"attachment[]?" id=?"attachment">?
]
*/

$.each($("input[name='attachment[]']"), function(i,v) {
    console.log(i);
    console.log(v); //v.val() does not exist... even uploaded a file and showing file

});

/* Output: 
0
<input type=?"file" name=?"attachment[]?" id=?"attachment">?
1
<input type=?"file" name=?"attachment[]?" id=?"attachment">?
2
<input type=?"file" name=?"attachment[]?" id=?"attachment">?
*/

return false;

Answers:

Answer

This should work:

$("input[name='attachment[]']").each(function() {
    var fileName = $(this).val().split('/').pop().split('\\').pop();
    console.log(fileName);
});

You can't get the full path of the file, because it depends on the browser you use. The only common cross-browser value for an input file is the name of the file.

Answer

I'd suggest something akin to the following:

?$('input:file').change(
    function(e){
        console.log(e.target.files[0].name);
    });???

JS Fiddle demo.

If you're allowing for multiple files to be uploaded, using the multiple attribute, then to get each of the names:

$('input:file').change(
    function(e){
        var f = e.target.files,
            len = f.length;
        for (var i=0;i<len;i++){
            console.log(f[i].name);
        }
    });?

JS Fiddle demo.

NOTE: in current browser versions, f[i].fileName should be f[i].name.

Answer

The <input type=file> element has a zero-indexed FileList accessed through its member variable files.

You can access that list through a query selector:

document.querySelector('input[type=file]').files 

And you can access the file name with dot notation:

document.querySelector('input[type=file]').files[0].name

It should be noted that in Chrome 53, Firefox 49, and the current W3C spec for the FileAPI, files is an Array-like list not an actual array. You can access each file object through its index, but you won't have access to any array prototypes without first converting the list to an array.

Answer

for

<input type="file" mutiple onchange="getSongs(this.files)"/>

use

function getSongs(files){
  ...
  for(var i = 0; i < files.length; i++){
     file=files[i];
     filename=file.fileName;
  }
}

if the input is just for single file, just use the name attribute

$("type=['file']").attr('name');

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.