Skip to content

Instantly share code, notes, and snippets.

@liabru
Created April 24, 2014 17:42
Show Gist options
  • Save liabru/11263124 to your computer and use it in GitHub Desktop.
Save liabru/11263124 to your computer and use it in GitHub Desktop.
Trigger a file open dialog and read local file in JavaScript
/*
* Trigger a file open dialog and read local file, then read and log the file contents
*/
var element = document.createElement('div');
element.innerHTML = '<input type="file">';
var fileInput = element.firstChild;
fileInput.addEventListener('change', function() {
var file = fileInput.files[0];
if (file.name.match(/\.(txt|json)$/)) {
var reader = new FileReader();
reader.onload = function() {
console.log(reader.result);
};
reader.readAsText(file);
} else {
alert("File not supported, .txt or .json files only");
}
});
fileInput.click();
@pmunin
Copy link

pmunin commented Jan 12, 2018

Is there any way to catch the event of cancelling open dialog?

@jcalvezar
Copy link

Hello, on Chrome the "change" event is not triggered the first time, just the second and so...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment