Open file dialog box in JavaScript

Viewed 432127

I need a solution to display open file dialog in HTML while clicking a div. The open file dialog box must open when the div is clicked.

I don't want to display the input file box as part of HTML page. It must be displayed in separate dialog, which is not a part of the web page.

13 Answers

Here is a nice one

Fine Uploader demo

It is an <input type='file' /> control itself. But a div is placed over that and css styles are applied to get that feel. Opacity of the file control is set to 0 so that it appears that the dialog window is opened when clicking on the div.

The simplest way:

#file-input {
  display: none;
}
<label for="file-input">
  <div>Click this div and select a file</div>
</label>
<input type="file" id="file-input"/>

What's important, usage of display: none ensures that no place will be occupied by the hidden file input (what happens using opacity: 0).

  1. Put input element type="file" anywhere on page and hide it with style="display:none". Give an id to input element. e.g. id="myid".
<input type="file" style="display:none" id="myid"/>
  1. Chose any div, image, button or any element which you want to use to open file dialog box, set an onclick attribute to it, like this:
<a href="#" onclick="document.getElementById('myid').click()"/>

AFAIK you still need an <input type="file"> element, then you can use some of the stuff from quirksmode to style it up

Here is a solution I developed after I failed to find a good solution

let input = document.createElement("input");
input.type = "file";
input.setAttribute("multiple", true);
input.setAttribute("accept", "image/*");
input.onchange = function (event) {
    //
    console.log(this.files);
};
input.click();

The only without <input type="file"> is by embedding a transparent flash movie over the div. You can then use a user generated click event (compliant with Flash 10 new security rules) to trigger a call to flash's FileReference.browse.

It offers an added dependency over the quirksmode way but in return you get alot more events (such as built in progress events).

May use

$('<input type="file" />').click()
Related