最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Trigger a file input to open via javascript - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Dec 23, 2010 at 6:32 gregghzgregghz 3,9657 gold badges45 silver badges71 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 3

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.

发布评论

评论列表(0)

  1. 暂无评论