Trigger a file input to open via javascript
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 int开发者_运维问答eract with the input directly?
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)
$('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.
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...
As far as I know opening the file open dialog from javascript is blocked for security reasons.
精彩评论