128

I have a hidden file input element. Is it possible to trigger its select file dialog box from a button's click event?

15 Answers 15

170

If you're looking to have your own button to upload a file instead of using <input type="file" />, you can do something like:

<input id="myInput" type="file" style="visibility:hidden" />
<input type="button" value="Show Dialog" onclick="$('#myInput').click();" />

Note that I used visibility: hidden, instead of display: none. You cannot call the click event on a non-displayed file input.

Sign up to request clarification or add additional context in comments.

5 Comments

Straightforward for basic cases, but not compatible with many browsers. Please note that its a much better idea to combine this solution with overlaying the file input element over a button at opacity:0, as it has been mentioned in Xeon06's answer.
Update: In modern browsers you can click an input that's not even in the DOM. Awesome!
i just tried click() on a display:none input and it worked
Yep, here in the year 2015, click()ing on an element with display: none works! ;) How things have changed in the last four years.
You can use hidden attribute instead style="visibility:hidden": <input id="myInput" type="file" hidden> (w3schools.com/tags/att_global_hidden.asp)
135

Most answers here are lacking a useful information:

Yes, you can programmatically click the input element using jQuery/JavaScript, but only if you do it in an event handler belonging to an event THAT WAS STARTED BY THE USER!

So, for example, nothing will happen if you, the script, programmatically click the button in an ajax callback, but if you put the same line of code in an event handler that was raised by the user, it will work.

P.S. The debugger; keyword disrupts the browse window if it is before the programmatical click ...at least in chrome 33...

8 Comments

as @LouisBataillard rightfully mentions: not only does the original event handler need to be initiated by the user; it must be specifically a click event. Here is a fiddle he provided demonstrating this: link
you can click something that is dynamically generated. in jquery, that is $(staticElementParent).on("click", "dynamicChild", function(){})
THANK YOU!!!! I've been testing all these answers in the javascript console and I've been going nuts!
I've been struggling for half an hour with programmatically prompting a file input window. NOBODY ELSE stated that it's impossible if the event isn't started by the user... you deserve a lot of +1.
As of Chrome 62 the debugger; keyword no longer disrupts the programmatic click
|
74

Just for the record, there is an alternative solution that does not require javascript. It is a bit of a hack, exploiting the fact that clicking on a label sets the focus on the associated input.

You need a <label> with a proper for attribute (points to the input), optionnaly styled like a button (with bootstrap, use btn btn-default). When the user clicks the label, the dialog opens, example :

<!-- optionnal, to add a bit of style -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

<!-- minimal setup -->
<label for="exampleInput" class="btn btn-default">
  Click me
</label>
<input type="file" id="exampleInput" style="display: none" />

5 Comments

I like this one, don't want to include full jQuery in my Angular project, works nice :)
is this behavior reliable in all modern browsers?
This works without any JS whatsoever, using native browser behavior. Paired with onDrop events, implementing a feature rich file upload works great!
I had to fiddle with the CSS but then it worked - namely the file input visibility having "display: none" is not ok in all browsers. (But opacity of 0, etc, can be used)
Add pointer-events: none; if you don't want accidental clicks on it. See zellwk.com/blog/hide-content-accessibly for a discussion of the accessibility implications of various options.
15

I'm not sure how browsers handle clicks on type="file" elements (security concerns and all), but this should work:

$('input[type="file"]').click();

I've tested this JSFiddle in Chrome, Firefox and Opera and they all show the file browse dialog.

2 Comments

This seems to work only when the "calling" event is itself a click event. For example it doesn't seem to be possible to open the file dialog based on a hover event: jsfiddle.net/UQfaZ/1
Do you know how this can be tested with Selenium if the input is not in the DOM?
11

Nowadays a hybrid solution like this can have the best experience,

let fileHandle;
async function fileOpen() {
    [fileHandle] = await window.showOpenFilePicker();
    const file = await fileHandle.getFile();
    console.log(await file.text());
}
// The advantage of this is fileHandle can be used to save to
// the opened file itself later, read more on this in https://web.dev/file-system-access/


// in April 2021, window.showOpenFilePicker still not support in Safari
// so one should have this around also
function legacyFileOpen() {
    var input = document.createElement('input');
    input.type = 'file';
    input.onchange = function () {
        input.files[0].arrayBuffer().then(function (arrayBuffer) {
            console.log(new TextDecoder().decode(arrayBuffer));
        });
    }
    input.click();
}

2 Comments

For anyone using the hybrid approach, you can do a check to see whether the "modern" fileOpen is supported with something like and decide which implementation to call based on the availability of the API. export const supportsShowOpenFilePicker = 'showOpenFilePicker' in window && typeof window.showOpenFilePicker === 'function';
Do note that as of 2025 window.showOpenFilePicker() is not yet supported in Firefox. However, the suggested legacyFileOpen-Function does work in Firefox. developer.mozilla.org/en-US/docs/Web/API/Window/… caniuse.com/?search=showOpenFilePicker
5

The best solution, works in all browsers.. even on mobile.

<div class="btn" id="s_photo">Upload</div>

<input type="file" name="s_file" id="s_file" style="opacity: 0;">';

<!--jquery-->

<script>
    $("#s_photo").click(function() {
        $("#s_file").trigger("click");
    });
</script>

Hiding the input file type causes problems with browsers, opacity is the best solution because it isn't hiding, just not showing. :)

3 Comments

you should mention that this requires a jquery reference.
Opacity involves a totally unrelated concept - you're just lucky if it doesn't affect your layout with an "see-through" element. The element should be there, but not visible, so visibility:hidden should be a better choice.
visibility: hidden still affects the layout. display: none is what you want.
4

I wrap the input[type=file] in a label tag, then style the label to your liking, and hide the input.

<label class="btn btn-default fileLabel" data-toggle="tooltip" data-placement="top" title="Upload">
    <input type="file">
    <span><i class="fa fa-upload"></i></span>
</label>

<style>
    .fileLabel input[type="file"] {
        position: fixed;
        top: -1000px;
    }
</style>

Purely CSS Solution.

1 Comment

Just set <input type="file" hidden> to remove the need to apply a CSS style.
3

Natively the only way is by creating an <input type="file"> element and then simulating a click, unfortunately.

There's a tiny plugin (shameless plug) which will take the pain away of having to do this all the time: file-dialog

fileDialog()
    .then(file => {
        const data = new FormData()
        data.append('file', file[0])
        data.append('imageName', 'flower')

        // Post to server
        fetch('/uploadImage', {
            method: 'POST',
            body: data
        })
    })

Comments

1

There is no cross browser way of doing it, for security reasons. What people usually do is overlay the input file over something else and set it's visibility to hidden so it gets triggered on it's own. More info here.

9 Comments

The OP is talking about <input type="file">, not <select>.
Not a problem. I've done it myself before. In response to your edit, there is a way to do it; by triggering the element's click event with jQuery $.click().
@JamWaffles okay that's weird. I clearly remember spending a whole day on this a few weeks back. It didn't work in Firefox and IE afair. I wonder what the deal was...
Curious. I have a JSFiddle in my answer that works with FF. I can't test in IE (I'm on Linux), so I don't know if that will still throw up.
Good research effort there! If I go a penny for every time web developers had to hack some pretty normal behaviour into something, I'd be filthy rich.
|
1

Make sure you are using binding to get component props in REACT

class FileUploader extends Component {
  constructor (props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
   onChange=(e,props)=>{
    const files = e.target.files;
    const selectedFile = files[0];
    ProcessFileUpload(selectedFile,props.ProgressCallBack,props.ErrorCallBack,props.CompleatedCallBack,props.BaseURL,props.Location,props.FilesAllowed);
  }
   handleClick = () => {
    this.refs.fileUploader.click();
  }
  render()
  {
  return(
      <div>
        <button type="button" onClick={this.handleClick}>Select File</button>  
        <input type='file' onChange={(e)=>this.onChange(e,this.props)} ref="fileUploader" style={{display:"none"}} />
      </div>)
  }
}

Comments

1

browse file programatically



function browseFile(accept) {
    const promise = resolvingPromise();
    const input = document.createElement('input');
    input.type = "file";
    input.accept = accept;
    input.onchange = function (e) {
        const files = e.target.files;
        promise.resolve(files);
    }
    setTimeout(function () {
        click(input);
    }, 0);
    return promise;
}

function click(node) {
    try {
        node.dispatchEvent(new MouseEvent('click'))
    } catch (e) {
        const evt = document.createEvent('MouseEvents')
        evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null)
        node.dispatchEvent(evt);
    }
}


Comments

0

Using jQuery you can call click() to simulate a click.

Comments

0

This worked for me:

$('#fileInput').val('');

Comments

0

For those who want the same but are using React

openFileInput = () => {
    this.fileInput.click()
}

<a href="#" onClick={this.openFileInput}>
    <p>Carregue sua foto de perfil</p>
    <img src={img} />
</a>
<input style={{display:'none'}} ref={(input) => { this.fileInput = input; }} type="file"/>

Comments

-1
<div id="uploadButton">UPLOAD</div>
<form action="[FILE_HANDLER_URL]" style="display:none">
     <input id="myInput" type="file" />
</form>
<script>
  const uploadButton = document.getElementById('uploadButton');
  const myInput = document.getElementById('myInput');

  uploadButton.addEventListener('click', () => {
    myInput.click();
  });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.