我如何以编程方式使用JavaScript打开文件选取器?
问题描述:
我天真地尝试了以下使用JavaScript以编程方式打开文件选取器(请参阅小提琴此处):
I have naively tried the following to open the file picker programmatically with JavaScript (see fiddle here):
<input type='file'>
<script>
$(function () {
$('input').click();
});
</script>
以上行不通。我怎样才能用JavaScript打开 input type ='file'
的文件选择器?
The above doesn't work. How can I open the file picker of a input type='file'
with JavaScript?
答
出于安全原因,您不能触发对话框,除非它是对某些用户触发事件的响应。您可以通过点击其他元素触发对话框:
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();
});
});
工作示例。