Javascript 无法获取输入类型=“文件”的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5903323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:26:37  来源:igfitidea点击:

Can't get value of input type="file"?

javascriptjqueryfileinput

提问by Danpe

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

我有一个 <input type="file" id="uploadPicture" value="123">

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

当我使用: alert($("#uploadPicture").val());

It alerts an empty dialog.

它会提醒一个空对话框。

采纳答案by Quentin

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

你可以读取它,但你不能设置它。value="123"将被忽略,因此在您单击它并选择一个文件之前它不会有任何值。

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

即便如此,该值也可能会被破坏,例如c:\fakepath\将用户文件系统的详细信息保密。

回答by Dmitry Vyprichenko

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

@BozidarS:现在FileAPI得到了很好的支持,并提供了许多有用的选项。

var file = document.forms['formName']['inputName'].files[0];
//file.name == "photo.png"
//file.type == "image/png"
//file.size == 300821

回答by Naresh.P

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

您可以使用 document.getElementById(); 获取它。

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

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

将给出文件的值,但它给出了 fakepath 如下

c:\fakepath\filename

回答by Hyman Marchetti

$('input[type=file]').val()

That'll get you the file selected.

这会让你选择文件。

However, you can't set the value yourself.

但是,您不能自己设置该值。

回答by marcosfromero

You can't set the valueof a fileinput in the markup, like you did with value="123".

你不能设置value一个的file输入标记,像你这样做value="123"

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

这个例子表明它确实有效:http: //jsfiddle.net/marcosfromero/7bUba/

回答by Bozidar Sikanjic

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....

不需要正则表达式,jQuery ....

回答by Md Shahriar

don't give this in file input value="123".

不要在文件输入值=“123”中给出这个。

  $(document).ready(function(){  

      var img = $('#uploadPicture').val();

  });