[javascript] Open file dialog box in JavaScript

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.

This question is related to javascript file dialog

The answer is


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).


Simple answer .

(1) Put input element type="file" anywhere on page and set attribute type="hidden" or style="display:none". Give an id to input element. e.g. id="myid"

(2) 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- onclick="document.getElementById('myid').click()"

That is all.


This is what worked best for me (Tested on IE8, FF, Chrome, Safari).

_x000D_
_x000D_
#file-input {_x000D_
  cursor: pointer;_x000D_
  outline: none;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  overflow: hidden;_x000D_
  filter: alpha(opacity=0); /* IE < 9 */_x000D_
  opacity: 0;_x000D_
}_x000D_
.input-label {_x000D_
  cursor: pointer;_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<label for="file-input" class="input-label">_x000D_
  Click Me <!-- Replace with whatever text or icon you wish to use -->_x000D_
  <input type="file" id="file-input">_x000D_
</label>
_x000D_
_x000D_
_x000D_

Explanation: I positioned the file input directly above the element to be clicked, so any clicks would either land on it or its label (which pulls up the upload dialog just as if you clicked the label itself). I had some issues with the button part of the default input sticking out of the side of the label, so overflow: hidden on the input and display: inline-block on the label were necessary.


Actually, you don't need all that stuff with opacity, visibility, <input> styling, etc. Just take a look:

<a href="#">Just click me.</a>
<script type="text/javascript">
    $("a").click(function() {
        // creating input on-the-fly
        var input = $(document.createElement("input"));
        input.attr("type", "file");
        // add onchange handler if you wish to get the file :)
        input.trigger("click"); // opening dialog
        return false; // avoiding navigation
    });
</script>

Demo on jsFiddle. Tested in Chrome 30.0 and Firefox 24.0. Didn't work in Opera 12.16, however.


_x000D_
_x000D_
    $("#logo").css('opacity','0');_x000D_
    _x000D_
    $("#select_logo").click(function(e){_x000D_
       e.preventDefault();_x000D_
       $("#logo").trigger('click');_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="select_logo">Select Logo</a> <input type="file" id="logo">
_x000D_
_x000D_
_x000D_

for IE add this:

$("#logo").css('filter','alpha(opacity = 0');

What if javascript is Turned Off on clients machine? Use following solution for all scenarios. You dont even need javascript/jQuery. :

HTML

<label for="fileInput"><img src="File_upload_Img"><label>
<input type="file" id="fileInput"></label>

CSS

#fileInput{opacity:0}  
body{
    background:cadetblue;
}

Explanation : for="Your input Id" . Triggers click event by default by HTML. So it by default triggers click event, no need of jQuery/javascript. If its simply done by HTML why use jQuery/jScript? And you cant tell if client disabled JS. Your feature should work even though JS is turned off.

Working jsFiddle (You dont need JS , jquery)


First add in the head tags:

<script>
   function showDialog(openFileDialog) {
       document.getElementById(openFileDialog).click();
   }
   function fileName(openFileDialog) {
       return document.getElementById(openFileDialog).value;
   }
   function hasFile(openFileDialog) {
       return document.getElementById(openFileDialog).value != "";
   }
   function fileNameWithoutFakePath(openFileDialog) {
       var fileName = document.getElementById(openFileDialog).value;
       return fileName.substr(fileName.lastIndexOf('\\') + 1);
   }
   function fakePathWithoutFileName(openFileDialog) {
       var fileName = document.getElementById(openFileDialog).value;
       return fileName.substr(0, fileName.lastIndexOf('\\'));
   }
</script>

if you already have script tags, just add these functions above.

In your body or form tags adding:

<input type="file" style="display:none" id="yourDesiredOrFavoriteNameForTheNewOpenFileDialogInstance"/>

No matter where in your html, is just like that you've created a new instance of type OpenFileDialog class as global variable, whose name is the id of the element, no matter where in your code or xaml, but in your script or code, you can't type his name, and then read a property or call a function, because there are global functions that do those that are not defined in the element input type="file". You just have to give these functions the id of the hidden input type="file" which is the name of the OpenFileDialog instance as string.

To ease your life in creating open file dialogs instances to your html, you can make a function that does it:

function createAndAddNewOpenFileDialog(name) {
     document.getElementById("yourBodyOrFormId").innerHtml += "<input type='file' style='display:none' id='" + name + "'/>"
}

and if you want to remove open file dialog, then you can make and use the following function:

function removeOpenFileDialog(name) {
    var html = document.getElementById("yourBodyOrFormId").innerHtml;
    html = html.replace("<input type='file' style='display:none' id='" + name + "'/>", "");
    document.getElementById("yourBodyOrFormId").innerHtml = html;
}

but before you remove open file dialog, ensure that it exists by making and using the following function:

function doesOpenFileDialogExist(name) {
    return document.getElementById("yourBodyOrFormId").innerHtml.indexOf("<input type='file' style='display:none' id='" + name + "'/>") != -1
}

and if you don't want to create and add the open file dialogs in the body or form tags in the html, because this is adding hidden input type="file"s, then you can do it in script using the create function above:

function yourBodyOrFormId_onload() {
    createAndAddNewOpenFileDialog("openFileDialog1");
    createAndAddNewOpenFileDialog("openFileDialog2");
    createAndAddNewOpenFileDialog("openFileDialog3");
    createAndAddNewOpenFileDialog("File Upload");
    createAndAddNewOpenFileDialog("Image Upload");
    createAndAddNewOpenFileDialog("bla");
    //etc and rest of your code
}

Ensure that near your body or form tags, you added:

onload="yourBodyOrFormId_onload()"

You don't have to do this line above, if you did it already.

TIP: You can add to your project or website new JScript File, if you don't have yet, and in this file you can put all the open file dialog functions away from the script tags and the html or web form page, and use them in your html or web form page from this JScript file, but don't forget before to link the html or web form page to the JScript File of course. You can do it just by dragging the JScript file to your html page in the head tags. If your page is web form and not simple html, and you don't have head tags, then put it anywhere so that it can work. Don't forget to define global variable in that JScript File, whose value will be your body or form id as string. After you linked the JScript file to your html or web form page, you can onload event of your body of form, set the value of that variable to your body or form id. Then in the JScript File, you don't have to give to the document the id of the body or form of one page anymore, just give it the value of that variable. You can call that variable bodyId or formId or bodyOrFormId or any other name you want.

Good luck man!


I dont't know why nobody has pointed this out but here's is a way of doing it without any Javascript and it's also compatible with any browser.


EDIT: In Safari, the input gets disabled when hidden with display: none. A better approach would be to use position: fixed; top: -100em.


<label>
  Open file dialog
  <input type="file" style="position: fixed; top: -100em">
</label>

If you prefer you can go the "correct way" by using for in the label pointing to the id of the input like this:

<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">

May use

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

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


The simplest way:

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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to dialog

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+) How to change DatePicker dialog color for Android 5.0 Android simple alert dialog Swift alert view with OK and Cancel: which button tapped? How to make a edittext box in a dialog How to check if activity is in foreground or in visible background? jquery ui Dialog: cannot call methods on dialog prior to initialization JavaScript: Create and save file Prevent Android activity dialog from closing on outside touch How to use OpenFileDialog to select a folder?