Open file dialog box in JavaScript

JavascriptFileDialog

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

    $("#logo").css('opacity','0');
    
    $("#select_logo").click(function(e){
       e.preventDefault();
       $("#logo").trigger('click');
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="select_logo">Select Logo</a> <input type="file" id="logo">

for IE add this:

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

Solution 2 - Javascript

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.

EDIT 2: A different approach would be to use opacity: 0. The problem is that it can mess with the layout. I added some CSS to the example to illustrate the problem.


label {
	display: inline-block;
	background: #ddd;
	border: 1px outset #ccc;
	border-radius: .3em;
	padding: .3em 1em;
	margin: .5em;
}

label:active {
  border-style: inset;
}

<label>
  Using <code>position: fixed</code>
  <input type="file" style="position: fixed; top: -100%">
</label>

<label>
  Using <code>opacity: 0</code>
  <input type="file" style="opacity: 0">
</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">

Solution 3 - Javascript

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.

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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

#file-input {
  cursor: pointer;
  outline: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  overflow: hidden;
  filter: alpha(opacity=0); /* IE < 9 */
  opacity: 0;
}
.input-label {
  cursor: pointer;
  position: relative;
  display: inline-block;
}

<label for="file-input" class="input-label">
  Click Me <!-- Replace with whatever text or icon you wish to use -->
  <input type="file" id="file-input">
</label>

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.

Solution 7 - Javascript

  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()"/>

Solution 8 - Javascript

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!

Solution 9 - Javascript

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)

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

May use

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArKView Question on Stackoverflow
Solution 1 - JavascriptSomwang SouksavatdView Answer on Stackoverflow
Solution 2 - JavascriptJP de la TorreView Answer on Stackoverflow
Solution 3 - JavascriptrahulView Answer on Stackoverflow
Solution 4 - JavascriptTigran SaluevView Answer on Stackoverflow
Solution 5 - JavascriptKarol SelakView Answer on Stackoverflow
Solution 6 - JavascriptChrisView Answer on Stackoverflow
Solution 7 - JavascriptNavin GiriView Answer on Stackoverflow
Solution 8 - Javascriptuser2133061View Answer on Stackoverflow
Solution 9 - JavascriptPratikView Answer on Stackoverflow
Solution 10 - JavascriptDan FView Answer on Stackoverflow
Solution 11 - JavascriptMartijn LaarmanView Answer on Stackoverflow
Solution 12 - JavascriptHamed Zakery MiabView Answer on Stackoverflow