I am trying to get file contents with FileReader(), JavaScript.
I find this answer: https://stackoverflow.com/a/21962101/2898694
As #Markasoftware said in comments, I am trying to save result to var.
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var myFile = evt.target.files[0];
var reader = new FileReader();
var result;
reader.readAsText(myFile);
reader.onload=function(){
result = reader.result;
console.log(result); // works
}
console.log(result); // not works
}
If I am trying to see content in onload handler all fine, but out of it I can't see result. Why?
Because onload runs asynchrone. console.log(result); // not works is executed before the onload event has fired.
More on that: How do I return the response from an asynchronous call?
example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
alert(imgUrl);
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" accept="image/jpeg,image/gif, image/png" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
</html>
Related
Good day,
I have the following code to load a ".TXT" file into a web page
function load(event) {
let fr = new FileReader();
fr.onload = function() {
let load0 = JSON.parse(fr.result);
console.log(load0);
console.log("Ready!");
};
fr.readAsText(event.target.files[0]);
}
function loadInput(event) {
document.getElementById("loadInputButton").click();
}
<html>
<body>
<input type="button" onclick="loadInput(event)" />
<input id="loadInputButton" type="file" accept="text" onchange="load(event)" />
</body>
</html>
It works fine but only once. After I once load the file it will not work anymore. I try to load the same file again but the function produces nothing.
May I ask for your help solving it?
Thank you,
Eugene
Clear the value of the input after using it, so that the change event will fire when you select the same file.
function load(event) {
let fr = new FileReader();
fr.onload = function() {
let load0 = JSON.parse(fr.result);
console.log(load0);
console.log("Ready!");
event.target.value = '';
};
fr.readAsText(event.target.files[0])
}
function loadInput(event) {
document.getElementById("loadInputButton").click();
}
<html>
<body>
<input type="button" onclick="loadInput(event)" />
<input id="loadInputButton" type="file" accept="text" onchange="load(event)" />
</body>
</html>
I'm currently learning JavaScript and I'm struggling to read a txt file and use its contents in the program, what I have so far:
fileBtn.addEventListener("change", function()
{
var content = [];
var file = fileBtn.files[0];
readFile(file, function(data)
{
console.log(JSON.parse(data));
//content.push(JSON.parse(data)) doesn't work, data is undef.
});
});
and a function readFile
function readFile(file, f)
{
var reader = new FileReader();
reader.onload = function(evt)
{
f(evt.target.result);
};
reader.readAsText(file);
}
My txt file is currenty only containing a "1", and it logs this number to the console but I can't work with it, if I try to push it into an array the values is suddenly undefined. My goal is to use the content of the file in the program later on
1 . no need to use JSON.parse if the text file only contain string .
data is containing all the text file content
2 . you need to put var content = [];
globally and not inside the function readFile
follow this snippet of code i think it will solve your problem
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<label for="file-upload" class="custom-file-upload">
Custom Upload
</label>
<input id="file-upload" type="file" />
<input id="log-content" type="button" value="Click Me"/>
</body>
<script>
var content = [];
function readFile(file, f) {
var reader = new FileReader();
reader.onload = function (evt) {
f(evt.target.result);
};
var text = reader.readAsText(file);
}
var fileBtn = document.getElementById("file-upload");
var logContnt = document.getElementById("log-content");
logContnt.addEventListener("click", function () {
alert(content);
})
fileBtn.addEventListener("change", function () {
var file = fileBtn.files[0];
readFile(file, function (data) {
content.push(data);
});
});
</script>
</html>
Can some one tell me why when all the File attributes are printed properly why FileReader.readAsArrayBuffer() is returning undefined in the following code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$( "#form" ).submit(function( event ) {
event.preventDefault();
var filevar=document.getElementById("file").files[0];
var reader=new FileReader() ;
console.log(filevar.name);
console.log(filevar.size);
console.log(filevar.type);
var file_contents= reader.readAsArrayBuffer(filevar);
console.log(file_contents);
});
});
</script>
<body>
<form action="" method="POST" id="form">
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br>
Choose File : <input name="myFile" type="file" id="file">
<input type="submit" id="submit">
</form>
</body>
</html>
Reading a file is asynchronous. You have to wait until it's done.
var reader = new FileReader();
reader.onload = function(e){
let value = e.value; // alternatively reader.result
// do stuff with your value
};
reader.readAsArrayBuffer(filevar);
.readAsArrayBuffer does not return anything.
Alternatively, you can set up an async function for that so you don't have to use callbacks:
function readFile(file){
return new Promise((res, rej) => {
// create file reader
let reader = new FileReader();
// register event listeners
reader.addEventListener("loadend", e => res(e.target.result));
reader.addEventListener("error", rej);
// read file
reader.readAsArrayBuffer(file);
});
}
async function main(file){
// read file into typed array
let fileArrayBuffer = new Uint8Array(await readFile(file));
// do things with it
console.log(fileArrayBuffer);
}
// register event listener for input
document.querySelector("input[type=file]").addEventListener("change", e => {
let file = e.target.files[0];
main(file);
});
<input type="file">
FileReader is actually an async function. Some files are larger than others and so you do not want to lock the main thread.
If you want to see the result of the file. You should add a call back to the onload function of the reader.
var reader = new FileReader();
reader.onload = function(completionEvent) {
console.log(completionEvent);
// Set the result to whatever you need it as
}
reader.readAsArrayBuffer(filevar);
I have a file reader that works on jfiddle but wont work in any browser. Im using all the latest browsers,. It will let me select the file, but nothing happens afterwards. Im very new to javascript.
javacript
<script type="text/javascript">
function readFile(file) {
var reader = new FileReader();
reader.onload = readSuccess;
function readSuccess(evt) {
var field = document.getElementById('main');
field.innerHTML = evt.target.result;
};
reader.readAsText(file);
}
document.getElementById('selectedFile').onchange = function(e) {
readFile(e.srcElement.files[0]);
};
</script>
html
<input type="file" id="selectedFile" />
<div id="main"></div>
jfiddle
http://jsfiddle.net/fstreamz/ngXBV/1/
Use window.onload or window.addEventListener("load")
<script type="text/javascript">
window.onload = function() {
function readFile(file) {
var reader = new FileReader();
reader.onload = readSuccess;
function readSuccess(evt) {
var field = document.getElementById("main");
field.innerHTML = evt.target.result;
};
reader.readAsText(file);
}
document.getElementById("selectedFile").onchange = function(e) {
readFile(e.srcElement.files[0]);
};
}
</script>
Here is the html
<input type="file" id="selectedFile" accept="text/plain" />
<div id="main"></div>
Is it possible to open a local file from a local page using FileReader without the <input type=file id=files>
The file is in the same directory as the page on a local machine.
reader = new FileReader();
reader.readAsText("output_log.txt");
I have created a sample code using Jquery/javascript which will read a local text file and display its content in Html page
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#fileinput").on('change',function(evt){
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
$("#filename").html(f.name);
$("#fileType").html(f.type);
$("#display_file_content").html(contents);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
});
});
</script>
</head>
<body>
<label>Please upLoad a file</label>
<input type="file" id="fileinput" />
</br>
<div>
<b>File Name:-</b><label id="filename"></label> </br>
<b>File Type:-</b><label id="fileType"></label></br>
<b>Content<b/>
<pre id="display_file_content">
</pre>
<div>
</body>
</html>