Show FileReader result in html page (not alert) - javascript

The fileReader function read my txt file from the sdcard and the result will be set in the evt.target.result.
I want to write (document.write) this evt.target.result to my html page. What is the best way to show this result on the screen. My filereader function:
function fileReader()
{
var reader = new FileReader();
reader.onload = win;
reader.onerror= fail;
reader.readAsText("/sdcard/mytest.txt");
function win(evt)
{
console.log(evt.target.result);
}
function fail(evt) {
console.log(evt.target.error.code);
}
};

You would need to have a div or something similar on your HTML page to display the result. There's tons of ways to present and style this, but the simplest would be to include the div in your HTML and reference it by id in your JS
<!DOCTYPE html>
<html>
<body>
<!-- Your results will display below -->
<div id="results"></div>
</body>
</html>
and in your JS do this
document.getElementById("results").innerHTML = evt.target.result;

Related

I am trying to read the file using javascript new fileReader()

I am trying to read the file using javascript new fileReader() function to convert the file in to binary format but is not supporting in Wix
please support us to resolve this issue to overcome it
var fr=new FileReader();
Hope This helps you :-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="file" />
<!-- writing JavaScript inside html -->
<body>
<input type="file" />
<!-- writing JavaScript inside html -->
<script>
const filename = document.querySelector('input[type="file"]');
filename.addEventListener('change', function (){
// Creating a FileReader object using the constructor.
const filereader = new FileReader();
// Reading a file as plain text
filereader.readAsText(filename.files[0]);
// Call this function to print the contents of the file
// once the file has been read.
filereader.onload = function {
console.log(filereader.result);
};
// Print the error incase there is one
filereader.onerror = function {
console.log("Error: ", filereader.error);
};
},false);
</script>
</body>
</body>
</html>
I think i have found a solution for you :-
try this
/* global FileReader */
$w.onReady(function () {
const fileReader = new FileReader();
fetch('https://static.wixstatic.com/media/e3b156_8646d72618e3420db36dba9156d0b8e7~mv2.jpg/v1/fit/w_512,h_586/o_0.jpeg')
.then(response => response.blob())
.then(blob => fileReader.readAsArrayBuffer(blob));
fileReader.onload = function () {
// your buffer array here. But why you need it? )))
console.log(fileReader.result);
}
})
Replace URL according to your needs.
Refer this Wix Corvid Api Overview

Getting text from file using FileReader on Load

So, I've been working on a page that uses only local files (server is not an option, unfortunately. Not even a localhost. The struggle is real.) and I've come to a situation where I need to grab text from a .csv file and populate it to the page. I have this bit of code that works, but I need to have a file set within the function when a button is pressed. Looking up the file manually isn't an option (to visualize what I'm doing, I'm making a mock database file in the most annoying way possible (because I have to, not because I want to)).
In the page I would have something like:
<button id="myButton" onclick="getText()"></button>
<script>
var myFile = "dataset.csv";
...
</script>
The following bit of code works (in regards to having it pull the data from the csv file), but, as I said, I need to pull the text from the file when a button is pressed and just have the file name set in the script, not pulling it up manually.
<!DOCTYPE html>
<html>
<body>
<input type="file" id="fileinput" />
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</body>
</html>
From what I can tell from the API, I would need to set the file attributes to a blob in order to pass it to FileReader. How I can do this without using an input box, I have no idea. There's also a 50% chance that I am completely wrong about this since I obviously don't know how to get this done.
If someone could show me how to achieve this with regards to what I'm looking for, it would be very much appreciated. I'm absolutely stumped.
Thank you.
Note: CORS restrictons will prevent this from working in most browsers. You can use FireFox Developer Edition, which disables CORS validation.
You can use an XMLHttpRequest to load a local file:
<!DOCTYPE html>
<html>
<body>
<button onclick="readSingleFile()">Click Me</button>
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile() {
let xhr = new XMLHttpRequest();
let url = "relative/path/to/file.txt;
if (!url) return;
xhr.onload = dataLoaded;
xhr.onerror = _ => "There was an error loading the file.";
xhr.overrideMimeType("text/plain");
xhr.open("GET",url);
xhr.send();
}
function dataLoaded(e){
var contents = e.target.responseText;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
</script>
</body>
</html>

FileReader onload not getting fired for second attempt in IE 11 after contents of the uploaded file is changed

FileReader onload not getting fired on second time when the same file still selected with IE11 but the contents of file has changed, it's getting fired all the time for FireFox,Chrome.
Operation Details
On First Click, its all okay for all browsers(but IE sometime still missing some words from file).
After that I changed the contents of the file.
And then I click second attempt to btnDownload, Firefox and Chrome still reading the updated contents. BUT IE DOES NOT WORK!
.html
<input type="file" id="fileSelect" style="" accept=".csv">
<a type="button" class="btn" id="btnDownload" onclick="csvDownload()"
download> CSV DOWNLOAD </a>
myjavascript.js
var fileInput = document.getElementById("fileSelect"); //<input type="file" id="fileSelect">
var result = "";
readFile = function() {
changeAPInfoName();
if (!isFileSupported()) {
console.log('The browser does not support the API.');
} else {
if (fileInput.files.length > 0) {
var reader = new FileReader();
reader.onload = function() {
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
}
reader.readAsText(fileInput.files[0]);
reader.onerror = function() {
console.log('The file cannot be read.'+fileInput.files[0].fileName);
};
}
// EVENT FOR DOWNLOAD BUTTON!!!!
function csvDownload(){
readFile();
// using ajax to sent info from files and get download file.
}
Please help me with following issue.
How can I get to the line in reader.onload method although file contents are changed. alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)"); .
Replace this
reader.onload = function() {
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
}
with
reader.addEventListener("load",function(){
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
});
I hope this is helpful. I was facing the same problem and I used this method and it worked
Example of working FileReader:
<html>
<head>
<script>
function read(){
//Select the element containing file
var file =document.querySelector('input[type=file]').files[0];
//create a FileReader
reader = new FileReader();
//add a listener
reader.addEventListener('load',function(){
alert(reader.result);
},false);
if(file){
//ReadFile
reader.readAsDataURL(file);//You can read it in many other forms
}
}
</script>
</head>
<body>
<input type="file" name="myFile" id="myFile" onchange="read()">
</body>
</html>
For more on FileReader check this document out : Link

To display text from a txt file using javascript

How to read text from a txt file with one button to browse the file and other button to display text. Pls help me in getting the code. i have tried many codes but othing worked. some code was like this. Thanks in advance
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "#":
output=output.split("\n").filter(/./.test, /\#/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
You should properly read an article like this: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Dont think this line is working properly:
output=output.split("\n").filter(/./.test, /\#/).join("\n");
Try changing it to:
output=output.split("\n").filter(function(l) {
//return /^\#/.test(l); // Starting with #
return l.indexOf('#') > -1; // Containing #
}).join("\n");
It would be interesting to see if this would work as well:
output=output.split("\n").filter(/\#/.test.bind(/\#/)).join("\n");
The second arguments passed to the .filter method is the context:
array.filter(callback[, thisObject])
Get the input file, use FileReader() to read it,on file load get text that matches the pattern. Finally display it through "main" div. Should work..
HTML :
<input id="fileInput" type="file"/>
<div id="main"></div>
jQuery :
$(function(){
$("#fileInput").change(function(e){
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output=output.split("\n").filter(/./.test, /\#/).join("\n");
$("#main").text(output);
};
reader.readAsText(myFile)
});
}
)
Demo

get the data of uploaded file in javascript

I want to upload a csv file and process the data inside that file. What is the best method to do so? I prefer not to use php script. I did the following steps. But this method only returns the file name instead of file path.So i didnt get the desired output.
<form id='importPfForm'>
<input type='file' name='datafile' size='20'>
<input type='button' value='IMPORT' onclick='importPortfolioFunction()'/>
</form>
function importPortfolioFunction( arg ) {
var f = document.getElementById( 'importPfForm' );
var fileName= f.datafile.value;
}
So how can i get the data inside that file?
The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.
See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
In this example, the user selects an HTML file. It is displayed in the <textarea>.
<form enctype="multipart/form-data">
<input id="upload" type=file accept="text/html" name="files[]" size=30>
</form>
<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>
<script>
function handleFileSelect(evt) {
let files = evt.target.files; // FileList object
// use the 1st file from the list
let f = files[0];
let reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
jQuery( '#ms_word_filtered_html' ).val( e.target.result );
};
})(f);
// Read in the image file as a data URL.
reader.readAsText(f);
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>
you can use the new HTML 5 file api to read file contents
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
but this won't work on every browser so you probably need a server side fallback.
The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.
function init() {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event) {
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
There exist some new tools on the blob itself that you can use to read the files content as a promise that makes you not have to use the legacy FileReader
// What you need to listen for on the file input
function fileInputChange (evt) {
for (let file of evt.target.files) {
read(file)
}
}
async function read(file) {
// Read the file as text
console.log(await file.text())
// Read the file as ArrayBuffer to handle binary data
console.log(new Uint8Array(await file.arrayBuffer()))
// Abuse response to read json data
console.log(await new Response(file).json())
// Read large data chunk by chunk
console.log(file.stream())
}
read(new File(['{"data": "abc"}'], 'sample.json'))
Try This
document.getElementById('myfile').addEventListener('change', function() {
var GetFile = new FileReader();
GetFile .onload=function(){
// DO Somthing
document.getElementById('output').value= GetFile.result;
}
GetFile.readAsText(this.files[0]);
})
<input type="file" id="myfile">
<textarea id="output" rows="4" cols="50"></textarea>
FileReaderJS can read the files for you. You get the file content inside onLoad(e) event handler as e.target.result.

Categories