Skip to content

Instantly share code, notes, and snippets.

@kcak11
Last active July 9, 2020 06:28
Show Gist options
  • Save kcak11/715429067bec56e45ea9d7a2a6c77267 to your computer and use it in GitHub Desktop.
Save kcak11/715429067bec56e45ea9d7a2a6c77267 to your computer and use it in GitHub Desktop.
JS FileReader Example

JavaScript FileReader Example

<input type="file" id="fileinput" />
<!--
© 2020 https://kcak11.com / https://ashishkumarkc.com
-->
var fileinput = document.getElementById("fileinput");
fileinput.addEventListener(
"change",
function (e) {
showContents(e.target.files[0], "readAsText");
showContents(e.target.files[0], "readAsBinaryString");
showContents(e.target.files[0], "readAsArrayBuffer");
showContents(e.target.files[0], "readAsDataURL");
e.target.value = "";
},
false
);
function getDisplayElement(elemId) {
var elem = document.getElementById(elemId);
if (elem) {
return elem;
}
elem = document.createElement("div");
elem.id = elemId;
elem.className = "displayElem";
document.body.appendChild(elem);
return elem;
}
function showContents(file, readType) {
try {
var reader = new FileReader();
reader.onload = function (event) {
var contents = event.target.result;
getDisplayElement(readType).scrollTop = 0;
getDisplayElement(readType).innerHTML =
"<h4>" + readType + ":</h4>" + contents;
};
reader.onerror = function (event) {
getDisplayElement(readType).innerHTML =
"<" +
readType +
"> File could not be read! Code " +
event.target.error.code;
};
reader[readType](file);
} catch (exjs) {
getDisplayElement(readType).innerHTML =
"<" + readType + "> File could not be read! : " + exjs;
console.log(exjs);
}
}
/*
© 2020 https://kcak11.com / https://ashishkumarkc.com
*/
/*
© 2020 https://kcak11.com / https://ashishkumarkc.com
*/
body {
font-family: Verdana;
}
input {
margin-bottom: 10px;
}
.displayElem {
border: 2px solid #000;
width: calc(100% - 20px);
height: 100px;
overflow: scroll;
margin-bottom: 20px;
word-break: break-word;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment