Last active
July 9, 2020 06:28
-
-
Save kcak11/715429067bec56e45ea9d7a2a6c77267 to your computer and use it in GitHub Desktop.
JS FileReader Example
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
<input type="file" id="fileinput" /> | |
<!-- | |
© 2020 https://kcak11.com / https://ashishkumarkc.com | |
--> |
JavaScript FileReader Example
A Pen by K.C.Ashish Kumar on CodePen.
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
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 | |
*/ |
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
/* | |
© 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