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
  • 104,438
  • 178
  • 489
  • 842

8 Answers8

89

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
  • 143,660
  • 29
  • 287
  • 307
  • 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
20

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
  • 524
  • 5
  • 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
  • 23,565
  • 5
  • 63
  • 86
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
  • 10,052
  • 12
  • 47
  • 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
  • 4,486
  • 8
  • 33
  • 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,465
  • 2
  • 21
  • 25
-3

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

coolguy
  • 7,866
  • 9
  • 45
  • 71