Created
April 24, 2014 17:42
-
-
Save liabru/11263124 to your computer and use it in GitHub Desktop.
Trigger a file open dialog and read local file in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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(); |
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
Is there any way to catch the event of cancelling open dialog?