I want to take a user uploaded a file in Javascript and extract data from it without submitting the page and process that data for giving other options in the form on the same page. It would be of great help if anyone could please help me out here.
Asked
Active
Viewed 1,851 times
0
-
Are you trying to [stop form submission](https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission)? – Jun 13 '18 at 04:23
-
I've read the question ten times, still have no clue what does it say ... – Teemu Jun 13 '18 at 04:24
-
No based on the contents of that file I have to set other form values. – Ayush Kothari Jun 13 '18 at 04:25
-
"_uploaded_" here means a file picked by user using `input type="file", and you wanted to access that file using JavaScript? – Teemu Jun 13 '18 at 04:26
-
what are you trying to do ? have you done anything so far ?. what type of file are you uploading ? – Akhil Aravind Jun 13 '18 at 04:27
-
you can look this link https://stackoverflow.com/questions/16505333/get-the-data-of-uploaded-file-in-javascript – rkj Jun 13 '18 at 04:32
2 Answers
3
Use the HTML 5 file API and FileReader, it allows you to work with files directly on the browser.
Here's a full example:
<input type="file" id="input" onchange="handleFiles(this.files)">
<div id="output">
</div>
<script type="text/javascript">
function handleFiles(files) {
//$("#output").html("got: "+files[0].name);
var reader = new FileReader();
reader.onload = function(e) {
$("#output").html(reader.result);
}
reader.readAsText(files[0]);
}
</script>
Please read this: https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications
and read this: https://www.w3.org/TR/FileAPI/#APIASynch
The FileReader class provides the following useful methods:
interface FileReader: EventTarget {
// async read methods
void readAsArrayBuffer(Blob blob);
void readAsBinaryString(Blob blob);
void readAsText(Blob blob, optional DOMString label);
void readAsDataURL(Blob blob);
....
Please read the above links, they will provide all the examples for you.

Max
- 1,049
- 7
- 9
1
Here is the example of how to access a file's content.
function handleFileSelect(evt) {
var files = evt.target.files;
var f = files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
// Do everything what you need with the file's content(e.target.result)
console.log(e.target.result);
};
})(f);
reader.readAsText(f);
}
document
.getElementById("upload")
.addEventListener("change", handleFileSelect, false);

teimurjan
- 1,875
- 9
- 18