45

I have a link,

<a id="upload-file">Upload your photo</a>

And if clicked, I want it to act as an browse file input

<input id="upload-file" type="file"/>

How would I accomplish this?

David542
  • 101,766
  • 154
  • 423
  • 727

8 Answers8

88

HTML

<input id="upload" type="file"/>
<a href="" id="upload_link">Upload your photo</a>​

CSS

#upload{
    display:none
}

JS

$(function(){
    $("#upload_link").on('click', function(e){
        e.preventDefault();
        $("#upload:hidden").trigger('click');
    });
});

​DEMO.

The Alpha
  • 138,380
  • 26
  • 281
  • 300
  • 3
    Really smart solution. Its clearly the right answer, and I would have spent hours trying to figure this out from scratch. Thanks. – usumoio Dec 31 '14 at 18:51
18

HTML Only

Here's a pretty simple answer that works with no CSS, Javascript/jQuery and doesn't rely on any framework infrastructure.

<label>
  <input type="file" style="display: none;">
  <a>Upload Photo link</a>
</label>

or even simpler

<label>
  <input type="file" style="display: none;">
  Upload Photo link
</label>
Jamie Armour
  • 496
  • 4
  • 10
7

following will solved the problem

html

<input id="upload-file" type="file"/>
<a id="fileupload">Upload your photo</a>

css

#upload-file{
    display: none;
}​

js

$("#fileupload").click(function(){
    $("#upload-file").click();
});​

http://jsfiddle.net/WXBKj/

Chamika Sandamal
  • 22,932
  • 5
  • 63
  • 83
4

You can do it without Javascript like this. cross-browser solution with attribute for :

DEMO

HTML

<label for="inputUpload" class="custom-file-upload">Upload your file</label>
<input id="inputUpload" type="file" />

CSS

#inputUpload {
    display: none;
}

.custom-file-upload {
    cursor: pointer;
    font-size: inherit;
    color: #0c090d;
}

.custom-file-upload:hover {
    text-decoration: underline;
}

DEMO

2

You can have a hidden <input> tag that you can then call $('#upload').click() on in order to simulate a click.

Or, you can have a hidden <input> tag that has an id, and then just add a label attribute to your link.

Ivan
  • 9,534
  • 12
  • 46
  • 78
1

In Angular 6, you can do like this,

<li class="list-group-item active cursor-pointer" (click)="file.click()">
    <i class="fas fa-cloud-upload-alt"></i> Upload <input type="file" #file hidden />
  </li>

When you click li html tag, the input button's click is triggered."hidden" attribute makes invisible.

Günay Gültekin
  • 3,908
  • 6
  • 31
  • 36
0

EDITED:

See This Demo: http://jsfiddle.net/rathoreahsan/s6Mjt/

JQUERY:

$("#upload").click(function(){
    $("#upload-file").trigger('click');
});

HTML

<a href="javascript:void(0)" id="upload">Upload your photo</a>
<input id="upload-file" type="file"/>

CSS

#upload-file {
    display:none;
}

OR

You may use nice plugins like this:

http://blueimp.github.com/jQuery-File-Upload/

Ahsan Rathod
  • 5,397
  • 2
  • 19
  • 25
-3

The best one http://valums.com/ajax-upload/

coolguy
  • 7,728
  • 9
  • 43
  • 71