Trigger a file input to open via javascript

2019-05-30 03:39发布

So I have an input, something like this:

<input type="file" id="file" />

I want to get the file open dialog to popup via javascript. I have tried things like this:

$('file').click();

(that's assuming I'm using something like prototype/mootools/jquery). However, this doesn't seem to do anything. Is there anyway I can trigger the click event for the file input without the user being forced to interact with the input directly?

4条回答
聊天终结者
2楼-- · 2019-05-30 04:19

As far as I know opening the file open dialog from javascript is blocked for security reasons.

查看更多
Summer. ? 凉城
3楼-- · 2019-05-30 04:21

I recall this is not possible due to it being a security feature. In fact, I'm pretty sure the button for the file browsing dialog does not even show up in the DOM (the field shows up, but not the button, which the browser renders automatically)

查看更多
唯我独甜
4楼-- · 2019-05-30 04:22

IIRC browsers don't allow this as a precaution mechanism. A script shouldn't be able to automatically upload a file in some way and tinkering with the File Open-dialog would be one of those ways.

Obviously this is bad in some situations...

查看更多
疯言疯语
5楼-- · 2019-05-30 04:27
$('file').click()

This works (in Chrome 8). You just need to make sure it's not set to display: none;

An easy solution is to position it absolute and then set left to something like -1000px.

查看更多
登录 后发表回答