Created
July 1, 2019 15:02
-
-
Save istiyakamin/13905bbd60e2520dd6c13884796541b8 to your computer and use it in GitHub Desktop.
File Data Read using Javascript (Client Side)
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
<html> | |
<head> | |
<meta http-equiv='Content-type' content='text/html;charset=UTF-8' > | |
<script> | |
function startRead() | |
{ | |
// obtain input element through DOM | |
var file = document.getElementById('file').files[0]; | |
if(file) | |
{ | |
getAsText(file); | |
} | |
} | |
function getAsText(readFile) | |
{ | |
var reader; | |
try | |
{ | |
reader = new FileReader(); | |
}catch(e) | |
{ | |
document.getElementById('output').innerHTML = | |
"Error: seems File API is not supported on your browser"; | |
return; | |
} | |
// Read file into memory as UTF-8 | |
reader.readAsText(readFile, "UTF-8"); | |
// Handle progress, success, and errors | |
reader.onprogress = updateProgress; | |
reader.onload = loaded; | |
reader.onerror = errorHandler; | |
} | |
function updateProgress(evt) | |
{ | |
if (evt.lengthComputable) | |
{ | |
// evt.loaded and evt.total are ProgressEvent properties | |
var loaded = (evt.loaded / evt.total); | |
if (loaded < 1) | |
{ | |
// Increase the prog bar length | |
// style.width = (loaded * 200) + "px"; | |
document.getElementById("bar").style.width = (loaded*100) + "%"; | |
} | |
} | |
} | |
function loaded(evt) | |
{ | |
// Obtain the read file data | |
var fileString = evt.target.result; | |
document.getElementById('output').innerHTML = fileString; | |
document.getElementById("bar").style.width = 100 + "%"; | |
} | |
function errorHandler(evt) | |
{ | |
if(evt.target.error.code == evt.target.error.NOT_READABLE_ERR) | |
{ | |
// The file could not be read | |
document.getElementById('output').innerHTML = "Error reading file..." | |
} | |
} | |
</script> | |
</head> | |
<body> | |
<input id="file" type="file" multiple onchange="startRead()"> | |
<h3>Progress:</h3> | |
<div style="width:100%;height:20px;border:1px solid black;"> | |
<div id="bar" style="background-color:#45F;width:0px;height:20px;"></div> | |
</div> | |
<h3>File contents:</h3> | |
<pre> | |
<code id="output"> | |
</code> | |
</pre> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment