Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulate a file upload click in jQuery

I have an <img ... /> tag that I have bound a click event to in jQuery. When it is clicked I'd like to have it emulate the click of a button on the file upload to open the file system browse pop-up. I've tried these things within the click function and had no success:

...
$(".hiddenUploadBtn").click();
...

...
$(".hiddenUploadBtn").select();
...

...
$(".hiddenUploadBtn").submit();
...
like image 988
Mark Ursino Avatar asked Jul 15 '09 18:07

Mark Ursino


3 Answers

Just wrap the img in a label and set the for attribute to the file input. Works for any kind of content and it's built into the spec. You can even hide the file input at that point.

<input type="file" id="fileUpload"><br>
<label for="fileUpload">
    <img src="https://www.google.com/images/srpr/logo11w.png" />
</label>
like image 193
Adam McCormick Avatar answered Oct 18 '22 09:10

Adam McCormick


Try this one using only javascript: http://code.google.com/p/upload-at-click/

Demo: http://upload-at-click.narod.ru/demo2.html

like image 41
John Wong Avatar answered Oct 18 '22 10:10

John Wong


This works for me

<input name="picture" type="file" onchange="alert(this.value)" class="file" size=20/>

for use upload button as image try this

<style>
div.fileinputs {position:relative; display:inline;}
div.fakefile {position:absolute; top:0px; left:0px; z-index:1;}
input.file {position:relative; text-align:right; -moz-opacity:0; filter:alpha(opacity: 0); opacity: 0; z-index:2;}
<style>

<div class="fileinputs">
  <input name="picture" type="file" onchange="alert(this.value)" class="file" size=1/>
  <div class="fakefile">
    <img src="images/browse.gif" align="middle" alt="browse" title="browse"/>
  </div>
</div>

so the input field is hidden, and when u click image - the selection dialog appears, but emulate this dialog from js imposible, yep. But you can also write the plugin/hack for browser)

like image 40
Bazuka Avatar answered Oct 18 '22 11:10

Bazuka