Skip to content

Instantly share code, notes, and snippets.

@louisbuchbinder
Created July 13, 2017 03:27
Show Gist options
  • Save louisbuchbinder/8ecbc083d0b0bab73d2028a59a45a3fe to your computer and use it in GitHub Desktop.
Save louisbuchbinder/8ecbc083d0b0bab73d2028a59a45a3fe to your computer and use it in GitHub Desktop.
Browser Files
if (!File) {
throw new Error('Unsupported Browser. File is required.');
}
function input(callback) {
var element = document.createElement('input');
element.setAttribute('type', 'file');
element.setAttribute('multiple', '');
element.addEventListener('change', function () {
callback([].slice.call(element.files));
});
element.click();
}
if (!FileReader) {
throw new Error('Unsupported Browser. FileReader is required.');
}
function read(file, type, callback) {
var reader = new FileReader;
if (!file) {
return void 0;
}
if (!type || !type.toLowerCase) {
return void 0;
}
if (!callback || typeof callback !== 'function') {
return void 0;
}
reader.addEventListener('load', function () {
callback(reader.result);
});
if (type.toLowerCase() === 'text') {
return reader.readAsText(file);
}
if (type.toLowerCase() === 'array' || type.toLowerCase() === 'array buffer') {
return reader.readAsArrayBuffer(file);
}
if (type.toLowerCase() === 'binary' || type.toLowerCase() === 'binary string') {
return reader.readAsBinaryString(file);
}
if (type.toLowerCase() === 'data' || type.toLowerCase() === 'data url') {
return reader.readAsDataURL(file);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment