How to get the filename from input type=file html

2019-02-11 20:44发布

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;

4条回答
老娘就宠你
2楼-- · 2019-02-11 21:13

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.

查看更多
We Are One
3楼-- · 2019-02-11 21:16

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');
查看更多
我命由我不由天
4楼-- · 2019-02-11 21:21

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.

查看更多
神经病院院长
5楼-- · 2019-02-11 21:36

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.

查看更多
登录 后发表回答