Read text file using FileReader - javascript

I've written the following code in an attempt to read the contents of a .txt file
<!DOCTYPE html>
<html>
<input type="file" id="files" name="file" />
<div id="container" style="height: 500px; min-width: 500px"></div>
<script>
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{
var reader = new FileReader();
reader.onload = (function(theFile)
{
var contents = theFile.target.result;
var lines = contents.split('\n');
})(f);
reader.readAsText(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</html>
Using firebug I set a break on var contents = theFile.target.result; but nothing is being returned. Can anyone spot what's wrong?
Thank you

Try (onload with closure):
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{
var reader = new FileReader();
reader.onload = (function(reader)
{
return function()
{
var contents = reader.result;
var lines = contents.split('\n');
//////
document.getElementById('container').innerHTML=contents;
}
})(reader);
reader.readAsText(f);
}
}
Or (without closure):
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{
var reader = new FileReader();
reader.onload = function(event)
{
// NOTE: event.target point to FileReader
var contents = event.target.result;
var lines = contents.split('\n');
//////
document.getElementById('container').innerHTML=contents;
};
reader.readAsText(f);
}
}

my 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 PreviewText() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadTextValue").value = oFREvent.target.result;
document.getElementById("obj").data = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var text = $('#uploadTextValue').val();
alert(text);
//here ajax
});
});
</script>
<object width="100%" height="400" data="" id="obj"></object>
<div>
<input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
<input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
</div>
Source file
</body>
</html>

Related

How to store lines into array after loading a selected local file in javascript

I'm trying to load a text file and store lines within the text file into an array variable. I found a related issue but I want to enhance it furtheremore
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="displayFile"></pre>
<script>
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('displayFile').innerText = reader.result;
myAddress.push(reader.result)
};
reader.readAsText(file);
});
</script>
and I want the lines that are read go into myAddress array
var myAddress = [];
var fileInput = document.getElementById('fileInput');
var myAddress = []
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('displayFile').innerText = reader.result;
myAddress = reader.result.split('\r\n')
};
reader.readAsText(file);
});

Reorder csv rows and columns

I have This csv file I want the output to be in a html table where the
Example :
fish;4;1;33 fish should be at 1 row column 4.
dog;5;2;66 dog should be at 2nd row column 5
I have come here:
var data ='Major;1;2;29/nMinor;2;3;29/nRowNum;1;1;23/njk;2;2;23/n44;1;‌4;23';
function insertData(id, data)
{
var table = document.getElementById(id);
var dataRows = data.split("/n");
if (table) {
dataRows.forEach(function(s) {
var x = s.split(';');
table.rows[x[2]].cells[x[1]].textContent = x[0];
}); }
This code inserts major and minor where it should but how can do the same by uploading a document?Basically var data = //uploaded doc
I have tried to do it with
myReader.onload = function(e) {
var content = myReader.result;
but no good result,I would really appreciate some help!
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
<script>
function myFunction(){
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
var data = e.target.result;
// You can process your file here
var datasplitted = data.split("/n");
// you do all you want
});
reader.readAsBinaryString(myFile);
}
});
}
</script>
</body>

How to convert an image into a Base64 string in a file?

I want to select multiple images and convert them to Base64 strings. I pushed the files into one array. My requirement is that after converting into Base64 strings, I want to push them into an array. I am not able to convert the images to Base64 strings.
$("input[name=property_images]").change(function() {
var names = [];
for (var i = 0; i < $(this).get(0).files.length; ++i) {
names.push($(this).get(0).files[i].name);
}
console.log(names);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="file" name="property_images" multiple="multiple" />
change your function to store the base64 value
$(document).ready(function(){
$("input[name=property_images]").change(function() {
var imgBase64Arr = [];
var files = this.files;
for (var i = 0; i < files.length; i++) {
(function(i){
var FR = new FileReader();
FR.onload = function(e) {
imgBase64Arr.push( e.target.result );//adding base64 value to array
if(i === files.length -1)//after all files are porcessed
submitData(imgBase64Arr)
};
FR.readAsDataURL(files[i]);
})(i);
}
});
function submitData(imgBase64Arr){
console.log(imgBase64Arr);
}
});
Here we have single image to convert base64 string.
function readFile() {
if (this.files) {
for(i=0;i<this.files.length;i++)
{
var FR= new FileReader();
FR.onload = function(e) {
//document.getElementById("img").src = e.target.result;
//document.getElementById("b64").innerHTML = e.target.result;
//$("#b64").append("<div></div>").html(e.target.result);
$('<img src="'+e.target.result+'" />').appendTo('#show-image');
$('<p>'+e.target.result+'</p>').appendTo('#text-image');
};
FR.readAsDataURL( this.files[i] );
}
}
}
document.getElementById("inp").addEventListener("change", readFile, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inp" type='file' multiple>
<div id='show-image'></div>
<div id='text-image'></div>

How to load image from directory, then show onclick

I am trying to have a function which has functions that do the following.
One function to store the files i get with input into the parent functions loadedimages array(loadimages).
One function to show those files in the correct component(showLoadedImages).
And one function to make the correct img file appear on the correct component.
The last function is what i want it to be like(it does not work).
The other two seem ok.
The problem i have is how to make the last function work while using the loadedimages array. You can change what i store in the array , i wouldnt mind.
Here is the JS code:
function imgviewer() {
"use strict";
var loadedimages = [];
var lidivs = [];
function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
break;
}
loadedimages.push(file);
}
}
function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;
//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
function showImage(index, elem) {
var chosenFile = loadedimages[index];
document.getElementById(elem).src = chosenFile;
}
document.getElementById('images').addEventListener('change', function(){
showLoadedImages("main");
}, false);
}
And some HTML
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg" width="1200" height="832" alt=""/></div>
<div id="main"></div>
When i call showLoadedImages("main") the images are shown in main div. I want to be able to click those images so that they appear on "willchange" .
This does what you asked for. There are a number of other issues with your code that you might want to address, starting with the images are not thumbnails at all (and shrunken images take just as long to load as the original), but perhaps I'm missing something.
"use strict";
var loadedimages = [];
var lidivs = [];
function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
continue;
}
loadedimages.push(file);
}
loadedimages.length || alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
}
function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;
//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img data-index="',
lidivs.length,
'" class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
span.addEventListener("click", foo );
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
function showImage(index, elem) {
document.getElementById(elem).src = lidivs[index].children[0].src;
}
function foo(event) {
showImage(event.target.dataset.index, "willchange");
}
function show() {
showLoadedImages("list");
}
function init() {
document.getElementById("images").addEventListener("change", show, false);
}
document.addEventListener( "DOMContentLoaded", init, false );
<body>
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg" width="1200" height="832" alt=""/></div>
</body>

Image preview does not work in IE and Firefox fine in Chrome

below code is working fine for Chrome but not for IE and FireFox. Please let me know if I am missing something in below.
<div style="height:0px;overflow:hidden">
<input type="file" id="profileimgload" name="profileimgload" onchange="PreviewImage();" accept="image/*" capture="camera" />
</div>
<img src="../../images/static/default_images/user_default.png" id = "uploadImageBoxImg" width="150" height="150" />
<span class="btn btn-xs btn-primary" align="center" onClick="addprofileimage()" title="change profile picture">upload</span>
</div>
javascript
//profile image upload
function addprofileimage()
{
$("#profileimgload").click();
}
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("profileimgload").files[0]);
alert("inside preview 2");
oFReader.onload = function (oFREvent) {
$("#uploadImageBoxImg").attr("src", oFREvent.target.result);
//document.getElementById("imageHiddenField").value = oFREvent.target.result;
};
};
First of all older versions of IE (9 and lower) don't support File API...
Also you better use oFReader.onloadend event instead of onload.
oFReader.onloadend = function () {
$("#uploadImageBoxImg").attr("src", oFReader.result);
}
Here is some useful documentation about File Reader API
Try this
function PreviewImage() {
var funcs = [];
var documentos = document.getElementById("uploadImage");
var tamanio = documentos.files.length;
for (var i = 0; i < tamanio; i++) {
funcs[i] = (function(index) {
return function(event) {
document.getElementById("uploadPreview" + index).src = event.target.result;
};
})(i);
}
var oFReader = new FileReader();
for (var k = 0; k < tamanio; k++) {
oFReader = new FileReader();
oFReader.readAsDataURL(documentos.files[k]);
oFReader.onload = funcs[k];
}

Categories

Resources