如何使用 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

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

How can I programmatically open the file picker with JavaScript?

javascriptgoogle-chrome

提问by Randomblue

Possible Duplicate:
In JavaScript can I make a “click” event fire programmatically for a file input element?

可能的重复:
在 JavaScript 中,我可以为文件输入元素以编程方式触发“点击”事件吗?

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();
    });
});

Working example.

工作示例

?

?

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

作为一项安全措施,您只能在用户输入时打开此类对话框,例如单击事件(在任何元素上)。您不能在页面加载时随机打开它。

http://jsfiddle.net/fEBFp/2/

http://jsfiddle.net/fEBFp/2/