Can't get value of input type=“file”?

2020-01-24 21:18发布

I have a <input type="file" id="uploadPicture" value="123">

When I'm using: alert($("#uploadPicture").val());

It alerts an empty dialog.

7条回答
再贱就再见
2楼-- · 2020-01-24 21:37

You can get it by using document.getElementById();

var fileVal=document.getElementById("some Id");
alert(fileVal.value);

will give the value of file,but it gives with fakepath as follows

c:\fakepath\filename
查看更多
叛逆
3楼-- · 2020-01-24 21:38

You can't set the value of a file input in the markup, like you did with value="123".

This example shows that it really works: http://jsfiddle.net/marcosfromero/7bUba/

查看更多
手持菜刀,她持情操
4楼-- · 2020-01-24 21:46

You can read it, but you can't set it. value="123" will be ignored, so it won't have a value until you click on it and pick a file.

Even then, the value will likely be mangled with something like c:\fakepath\ to keep the details of the user's filesystem private.

查看更多
萌系小妹纸
5楼-- · 2020-01-24 21:54

It's old question but just in case someone bump on this tread...

var input = document.getElementById("your_input");
var file = input.value.split("\\");
var fileName = file[file.length-1];

No need for regex, jQuery....

查看更多
女痞
6楼-- · 2020-01-24 21:55

@BozidarS: FileAPI is supported quite well nowadays and provides a number of useful options.

var file = document.forms['formName']['inputName'].files[0];
//file.name == "photo.png"
//file.type == "image/png"
//file.size == 300821
查看更多
再贱就再见
7楼-- · 2020-01-24 21:59
$('input[type=file]').val()

That'll get you the file selected.

However, you can't set the value yourself.

查看更多
登录 后发表回答