Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript is it possible to launch a file browser dialog programmatically?

Instead of using the <input type="file"> tag I'd like to have a button that launches a file browser dialog.

My first thought was to have a hidden file input tag and a button. I'd use the button click on the button to fire the onclick of the hidden file input, but I haven't been able to get this working properly.

So the question is, is this even possible? And second is there a nicer way to do this and still be able to send the information back in a form?

This will be the bottom layer of degrading functionality (from Flash to JavaScript (our site doesn't work without JS)) so it has to work with just basic JS and HTML.

like image 688
user28655 Avatar asked Oct 16 '08 17:10

user28655


People also ask

How to Open file dialog in JavaScript?

Use the type="file" Attribute in HTML and onchange Method in JavaScript to Open File Dialog. We will create a button element in the following instance, and an onclick attribute will follow this. This will trigger a function in the JavaScript file.

Can JavaScript open a local file?

JavaScript cannot typically access local files in new browsers, but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.


1 Answers

I'd rather avoid transparency tricks.

This worked for me (uses jQuery):

$("#upload-box").change(function(){
    $("#upload-click-handler").val($(this).val());
});
$("#upload-click-handler").click(function(){
    $("#upload-box").click();
});

And the HTML:

<input id="upload-box" style="visibility:hidden;height:0;" name="Photo" type="file" />
<input id="upload-click-handler" type="text" readonly />

It creates a text input, and a hidden upload input, and patches (=routes) the click on the text input to the hidden file input.

When a file is selected, it will write back the name of the file in the text input, in line with what most users would expect from the interface.

Should work on FF, Chrome, IE9 and +. I didn't test it on IE8.

Here's a jsfiddle. Thank you for upvoting my answer if you like it.

like image 88
Rolf Avatar answered Oct 26 '22 13:10

Rolf