[javascript] How to open select file dialog via js?

$('#id').click();

It doesn't work on Chrome 26 on Mac OS.

The problem actually is creation "upload" widget that can be integrated in a form. Widget will consists of two parts. The first part is div with initiator button and error/success messages. I think the way is put another form as the second part with file input and submit file into the iframe. After submition we fill hidden field in first part in main form or show errors in the same.

Easy way is adding file-form into main-form, but it's prohibited.

This question is related to javascript jquery html

The answer is


First Declare a variable to store filenames (to use them later):

var myfiles = [];

Open File Dialog

$('#browseBtn').click(function() {
    $('<input type="file" multiple>').on('change', function () {
        myfiles = this.files; //save selected files to the array
        console.log(myfiles); //show them on console
    }).click();
});

i'm posting it, so it may help someone because there are no clear instructions on the internet to how to store filenames into an array!


_x000D_
_x000D_
function promptFile(contentType, multiple) {
  var input = document.createElement("input");
  input.type = "file";
  input.multiple = multiple;
  input.accept = contentType;
  return new Promise(function(resolve) {
    document.activeElement.onfocus = function() {
      document.activeElement.onfocus = null;
      setTimeout(resolve, 500);
    };
    input.onchange = function() {
      var files = Array.from(input.files);
      if (multiple)
        return resolve(files);
      resolve(files[0]);
    };
    input.click();
  });
}
function promptFilename() {
  promptFile().then(function(file) {
    document.querySelector("span").innerText = file && file.name || "no file selected";
  });
}
_x000D_
<button onclick="promptFilename()">Open</button>
<span></span>
_x000D_
_x000D_
_x000D_


In HTML only:

<label>
  <input type="file" name="input-name" style="display: none;" />
  <span>Select file</span>
</label>

Edit: I hadn't tested this in Blink, it actually doesn't work with a <button>, but it should work with most other elements–at least in recent browsers.

Check this fiddle with the code above.


With jquery library

<button onclick="$('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">

READY TO USE FUNCTION (using Promise)

/**
 * Select file(s).
 * @param {String} contentType The content type of files you wish to select. For instance "image/*" to select all kinds of images.
 * @param {Boolean} multiple Indicates if the user can select multiples file.
 * @returns {Promise<File|File[]>} A promise of a file or array of files in case the multiple parameter is true.
 */
function (contentType, multiple){
    return new Promise(resolve => {
        let input = document.createElement('input');
        input.type = 'file';
        input.multiple = multiple;
        input.accept = contentType;

        input.onchange = _ => {
            let files = Array.from(input.files);
            if (multiple)
                resolve(files);
            else
                resolve(files[0]);
        };

        input.click();
    });
}

TEST IT

_x000D_
_x000D_
// Content wrapper element_x000D_
let contentElement = document.getElementById("content");_x000D_
_x000D_
// Button callback_x000D_
async function onButtonClicked(){_x000D_
    let files = await selectFile("image/*", true);_x000D_
    contentElement.innerHTML = files.map(file => `<img src="${URL.createObjectURL(file)}" style="width: 100px; height: 100px;">`).join('');_x000D_
}_x000D_
_x000D_
// ---- function definition ----_x000D_
function selectFile (contentType, multiple){_x000D_
    return new Promise(resolve => {_x000D_
        let input = document.createElement('input');_x000D_
        input.type = 'file';_x000D_
        input.multiple = multiple;_x000D_
        input.accept = contentType;_x000D_
_x000D_
        input.onchange = _ => {_x000D_
            let files = Array.from(input.files);_x000D_
            if (multiple)_x000D_
                resolve(files);_x000D_
            else_x000D_
                resolve(files[0]);_x000D_
        };_x000D_
_x000D_
        input.click();_x000D_
    });_x000D_
}
_x000D_
<button onclick="onButtonClicked()">Select images</button>_x000D_
<div id="content"></div>
_x000D_
_x000D_
_x000D_


For the sake of completeness, Ron van der Heijden's solution in pure JavaScript:

<button onclick="document.querySelector('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">

JS only - no need for jquery

Simply create an input element and trigger the click.

var input = document.createElement('input');
input.type = 'file';
input.click();

This is the most basic, pop a select-a-file dialog, but its no use for anything without handling the selected file...

Handling the files

Adding an onchange event to the newly created input would allow us to do stuff once the user has selected the file.

var input = document.createElement('input');
input.type = 'file';

input.onchange = e => { 
   var file = e.target.files[0]; 
}

input.click();

At the moment we have the file variable storing various information :

file.name // the file's name including extension
file.size // the size in bytes
file.type // file type ex. 'application/pdf'

Great!

But, what if we need the content of the file?

In order to get to the actual content of the file, for various reasons. place an image, load into canvas, create a window with Base64 data url, etc. we would need to use the FileReader API

We would create an instance of the FileReader, and load our user selected file reference to it.

var input = document.createElement('input');
input.type = 'file';

input.onchange = e => { 

   // getting a hold of the file reference
   var file = e.target.files[0]; 

   // setting up the reader
   var reader = new FileReader();
   reader.readAsText(file,'UTF-8');

   // here we tell the reader what to do when it's done reading...
   reader.onload = readerEvent => {
      var content = readerEvent.target.result; // this is the content!
      console.log( content );
   }

}

input.click();

Trying pasting the above code into your devtool's console window, it should produce a select-a-file dialog, after selecting the file, the console should now print the contents of the file.

Example - "Stackoverflow's new background image!"

Let's try to create a file select dialog to change stackoverflows background image to something more spicy...

var input = document.createElement('input');
input.type = 'file';

input.onchange = e => { 

   // getting a hold of the file reference
   var file = e.target.files[0]; 

   // setting up the reader
   var reader = new FileReader();
   reader.readAsDataURL(file); // this is reading as data url

   // here we tell the reader what to do when it's done reading...
   reader.onload = readerEvent => {
      var content = readerEvent.target.result; // this is the content!
      document.querySelector('#content').style.backgroundImage = 'url('+ content +')';
   }

}

input.click();

open devtools, and paste the above code into console window, this should pop a select-a-file dialog, upon selecting an image, stackoverflows content box background should change to the image selected.

Cheers!


To expand on the answer from 'levi' and to show how to get the response from the upload so you can process the file upload:

selectFile(event) {
    event.preventDefault();

    file_input = document.createElement('input');
    file_input.addEventListener("change", uploadFile, false);
    file_input.type = 'file';
    file_input.click();
},

uploadFile() {
    let dataArray = new FormData();
    dataArray.append('file', file_input.files[0]);

    // Obviously, you can substitute with JQuery or whatever
    axios.post('/your_super_special_url', dataArray).then(function() {
        //
    });
}

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 jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment