Open file selection box when click a link or an image

Sometimes you will meet requirements like this:

I want someone to click on a link/an image and the file selection box will open immediately.  Then user can upload an image through AJAX.  (Think Facebook cover photo upload)

At first, it seems that it is easy.  Here is what I did:

<input type="file" id="file1" name="file1" style="display:none;" />
<a href="javascript:;" onclick="$('#file1').click()">Some link text</a>

It seems perfect when you combined it with jQuery upload.  But I was wrong.  As of this writing, the above lines work in FF v.17 and Chrome v.23, but it does not work in IE9.  It will prompt:

SCRIPT5: Access is denied

It is definitely NOT cross domain problem.  It turns out that it is a bug in IE (Original link).

So, how to solve this:

The answer is quite counter-intuitive.  Here are the steps to do so:

  1. Create an <input type="file" /> tag, but this time, do not use display:none or visibility:hidden, but set opacity of this input tag to 0 (invisible) (Here is how to do it in FF/Chrome and IE).
  2. Create a simple <a> link
  3. Create a javascript: when mouseover this <a> link, the invisible <input> will go over the <a> link, so that, when use click on a link, he actually clicks on the invisible <input>.
  4. A file selection box is shown.  jQuery.upload is running again!
This "Tricks" works under all major browsers: IE, FF and Chrome.

Hope it helps someone.

By the person who spend 3 days to figure this out...


Popular posts from this blog

TCPDF How to show/display Chinese Character?

Wordpress Load balancing: 2 web servers 1 MySQL without any Cloud services

Using wget bypass htaccess username password 401 authorization