如何使用 JavaScript 以编程方式打开文件选择器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12134014/
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
How can I programmatically open the file picker with JavaScript?
提问by Randomblue
Possible Duplicate:
In JavaScript can I make a “click” event fire programmatically for a file input element?
I have naively tried the following to open the file picker programmatically with JavaScript (see fiddle here):
我天真地尝试了以下使用 JavaScript 以编程方式打开文件选择器(请参阅此处的小提琴):
<input type='file'>?
<script>
$(function () {
$('input').click();
});
</script>
The above doesn't work. How can I open the file picker of a input type='file'
with JavaScript?
以上是行不通的。如何input type='file'
使用 JavaScript打开 a 的文件选择器?
回答by Christofer Eliasson
For security reasons you can't trigger the dialog, unless it is as a response to some user triggered event. You could for instance trigger the dialog through a click on some other element:
出于安全原因,您不能触发对话框,除非它是作为对某些用户触发事件的响应。例如,您可以通过单击其他元素来触发对话框:
$(function () {
$(".someElement").click(function () {
$('#f').click();
});
});
工作示例。
?
?
回答by pimvdb
As a security measure, you can only open such dialogs on an user input, such as a click event (on whatever element). You cannot open it randomly such as on page load.
作为一项安全措施,您只能在用户输入时打开此类对话框,例如单击事件(在任何元素上)。您不能在页面加载时随机打开它。