Trigger a file input to open via javascript

2019-05-30 03:33发布

问题:

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?

回答1:

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)



回答2:

$('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.



回答3:

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



回答4:

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