通过 jquery 设置 type="file" 的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12189953/
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
Set value of type="file" via jquery
提问by Shree
Note:
The answer(s) below reflect the state of legacy browsers in 2009. Now you can actually set the value of the file input element dynamically/programatically using JavaScript in 2017.
See the answer in this question for details as well as a demo:
How to set file input value programatically (i.e.: when drag-dropping files)?
笔记:
下面的答案反映了 2009 年旧浏览器的状态。 现在您实际上可以在 2017 年使用 JavaScript 以动态/编程方式设置文件输入元素的值。
有关详细信息以及演示,请参阅此问题中的答案:
如何以编程方式设置文件输入值(即:拖放文件时)?
Without upload(browse) a file I want to set a value of fileuploader
through button click.Is it possible or I am in wrong way?
sample html:
没有上传(浏览)一个文件,我想fileuploader
通过按钮点击设置一个值。这可能还是我的方式不对?
示例 html:
<input type="file" id="files" />
<input type="button" id="btnTest" value="Test"/>
and jquery:
和jQuery:
$("#btnTest").click(function() {
alert('test');
//$('#files').html('pp.img');
//$('#files').val('pp.img');
$('#files').text('pp.img')
});
But its not work for me .
但它对我不起作用。
采纳答案by rahul
well i must say that there is no cross-browser way to do this. The "no file selected" text is in the implementation-defined part of the widget, and it's totally browser specific. and if it is necessary You could simply use CSS to cover the text with something when the value attribute is empty.
好吧,我必须说没有跨浏览器的方式来做到这一点。“未选择文件”文本位于小部件的实现定义部分,它完全特定于浏览器。如果有必要,当 value 属性为空时,您可以简单地使用 CSS 来覆盖文本。
回答by zzzzBov
Is it possible?
是否可以?
nope
不
It would be a serious security flaw if you were able to do this via JavaScript, as you'd be able to specify any file on a user's computer, which is why you're not allowed to set the value of a file input element.
如果您能够通过 JavaScript 执行此操作,这将是一个严重的安全漏洞,因为您可以指定用户计算机上的任何文件,这就是为什么您不能设置文件输入元素的值的原因。
回答by Marc
I don't think you are allowed to set the value at all. Because if you were able to, you could put C:\passwords.txt
in there and submit the value automatically. Not very secure.
我认为您根本不允许设置该值。因为如果可以,您可以将其放入C:\passwords.txt
并自动提交值。不是很安全。