Need help to generate three blocks using loop - javascript

Following 3 block of code, want to generate using loop/array to make short code.I know use of loop is not a big thing, but for me its difficult to change counter with variable "openFile", I want counter increment with variable "openFile" like openFile1, openFile2 and openFile3 with each iteration of loop.
$(function() {
var openFile1 = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('img1');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
var openFile2 = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('img2');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
var openFile3 = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('img3');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
});

Just create a function that takes count as arg and return a function that takes just event as arg. due to closure, the value of 'count' given when calling openFile with a given value of count will be used for the inner function.
var openFileFunc = function(count) {
return
function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('img'+(count+1));
output.src = dataURL;
};
reader.readAsDataURL(input.files[count]);
};
}
Now you can get the three functions equivalent to what you did by calling a map like this:
var functions = [1,2,3].map(openFileFunc)
Each function in this array is the same as what you had.

var openFile = function(arrOfCount){
var reader;
for(i=0;i<arrOfCount;i++){
reader= new FileReader();
return function(event){
var input = event.target;
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('img'+(i+1));
output.src = dataURL;
};
reader.readAsDataURL(input.files[i]);
}
}
}

May be this will work for you.
function callFunctionNtimes(totalCount){
for(start=1;i<=totalCount;i++)
{
var filevar = 'openFile'+start;
filevar = function(event)
{
var input = event.target;
var reader = new FileReader();
reader.onload = function()
{
var dataURL = reader.result;
var output = document.getElementById('img'+start);
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
}
}
//to call n time below function
var totalCount = 3;
callFunctionNtimes(totalCount);

I have tried to generalize code
var allImages = document.getElementsByClassName("my-images");
for (var i = 0; i < allImages.length; i++) {
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = allImages[i];
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
}
But still it seems you have 3 file upload controls and you want to display preview for each, is it so?

Related

How to call a function that gives a url, which is then used to store and display an image using FileReader

I am new to coding in javascript, I have been tasked as an excersise using some pre-existing functions to create an image item using a given url. I need to read the image, store it in local storage and then display it on the screen. The only functionI need to add too is process file. I am stuck and cannot get it to display the image. I get an error saying that the path does not exist. Below is my code, any guidance to what I am doing wrong? I feel like I am very close but doing something funamendatly wrong.
function addImageEntry(key, url) {
var imgElement = new Image();
imgElement.alt = "Photo entry";
imgElement.src = url;
addSection(key, imgElement);
}
function makeItem(type, data) {
var itemObject = { type: type, data: data };
return JSON.stringify(itemObject);
}
function processFile(event) {
function addImage(url) {
var key = "diary" + Date.now();
addImageEntry(key, url);
var imgElement = new Image();
imgElement.src = url;
var item = makeItem("image", imgElement.src);
localStorage.setItem(key, item);
}
var inputElement = event.target;
var fileObject = inputElement.files[0];
var reader = new FileReader();
reader.addEventListener("load",addImage);
url = reader.readAsDataURL(fileObject);
event.target.value = "";
}
The url = reader.readAsDataURL(fileObject) won't store the image data.
It stores in reader.result.
Use imgElement.src = reader.result.
document.querySelector('input[type="file"]').addEventListener('change', processFile)
function processFile(event) {
var fileObject = event.target.files[0]
var reader = new FileReader()
reader.addEventListener('load', addImage)
reader.readAsDataURL(fileObject)
function addImage() {
var imgElement = new Image()
imgElement.src = reader.result
document.body.append(imgElement)
}
}
Amend:
function addImage(event) {
// use reader.result is ok too
localStorage.setItem('myimage', event.target.result)
}
function addImageEntry() {
var imgElement = new Image()
imgElement.src = localStorage.getItem('myimage')
imgElement.style.display = 'block'
document.body.append(imgElement)
}

How block on File Choose Dialog or get the Upload Button Event?

function importcsv(arg) {
$("#upload:hidden").trigger('click');
var fileVal=document.getElementById("upload");
var filePath = fileVal.value;
var fr = new FileReader();
var result ="";
fr.readAsText(fileVal.files[0]);
fr.onload = function(e) {
result=e.target.result;
post("worker.php?arg="+arg,result);
};
return true;
}
why this is only on second clic, choose and up file? first call the filePath var is empty...how i can block until file is choosen?
I guess your problem is that you put your trigger at the very first line. Move that to the last position like :
function importcsv(arg) {
var fileVal=document.getElementById("upload");
var filePath = fileVal.value;
var fr = new FileReader();
var result ="";
fr.readAsText(fileVal.files[0]);
fr.onload = function(e) {
result=e.target.result;
post("worker.php?arg="+arg,result);
};
$("#upload:hidden").trigger('click');
return true;
}

How to to base 64 encode in two images in same file

Here i have two form fields , in this i want to convert the base 64 encode from image,and after that i want to pass in JSON Format to next URL, i tried like this but i am not getting ,some time i am getting one filed value (encoded value) uncaught error property_img , i don't know how to do anyone help me pls
var files = document.getElementById('floorplan_img').files;
if (files.length > 0) {
var file = files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
console.log(reader.result);
var base64 = reader.result;
var str = base64;
var arr = str.split(",");
var floor_img = arr[1];
console.log(floor_img);
};
reader.onerror = function(error) {
console.log('Error: ', error);
};
}
var files1 = document.getElementById('upload_properties').files;
if (files1.length > 0) {
var file1 = files1[0];
var reader1 = new FileReader();
reader1.readAsDataURL(file1);
reader1.onload = function() {
var base64_img = reader1.result;
var str_64 = base64_img;
var arr_str = str_64.split(",");
var property_img = arr_str[1];
console.log(property_img);
};
reader1.onerror = function(error) {
console.log('Error: ', error);
};
}
<input type="file" id="floorplan_img">
<input type="file" id="upload_properties">
Try this:
var reader = new FileReader();
reader.onload = function(event) {
var src= event.target.result;
console.log(src);
};

FileReader's onloadend event is never triggered

I'm trying to make a small snippet to preview images before uploading them:
$.fn.previewImg=function($on){
var input = this;
try{
if (this.is("input[type='file']")) {
input.change(function(){
var reader = new FileReader();
reader.onloadend = function(){
for (var i = 0; i < $on.length; i++) {
if (/img/i.test($on[i].tagName)) $on[i].src = reader.result;
else $on[i].style.bakgroundImage = "url("+reader.result+")";
}
};
});
}else throw new exception("Trying to preview image from an element that is not a file input!");
}catch(x){
console.log(x);
}
};
I'm calling it like:
$("#file").previewImg($(".preview_img"));
but the onloadend function is never called.
FIDDLE
Actually , you got to specify the file and instruct the fileReader to read it.
Below is the corrected code.
$.fn.previewImg=function($on){
var input = this;
try{
if (this.is("input[type='file']")) {
input.change(function(evt){
var reader = new FileReader();
console.log("Input changed");
reader.onloadend = function(){
console.log("onloadend triggered");
for (var i = 0; i < $on.length; i++) {
if (/img/i.test($on[i].tagName)) $on[i].src = reader.result;
else $on[i].style.bakgroundImage = "url("+reader.result+")";
}
};
//get the selected file
var files = evt.target.files;
//instruct reader to read it
reader.readAsDataURL(files[0]);
});
}else throw new exception("Trying to preview image from an element that is not a file input!");
}catch(x){
console.log(x);
}
};
$("#file").previewImg($(".preview_img"));

Get file name in javascript

Hi I have a input file which takes multiple files and the tag is given the Id = fileToUpload
and here goes the code:
var input = document.getElementById('filesToUpload');
for (var x = 0; x < input.files.length; x++) {
oFReader = new FileReader();
oFReader.readAsDataURL(input.files[x]);
oFReader.onload = function (oFREvent) {
imageSrc = oFREvent.target.result;
console.log("source:" +imageSrc);
name = oFREvent.target.name;
console.log("name:" +name);
};
}
Here I am able to get the source of the image but I am not able to get the name of the file which is selected for uploading. I am doing the right way or this is not a right way to get a file name.
You want to get the name from the original filelist, not the target of the FileReader's onload event. The FileReader object doesn't have a name property and the target of the onload event is the FileReader, not the file.
EDIT
Getting the name file loaded into the FileReader turns out to be kinda tricky! I came up with two ways which you can see in this fiddle.
First way just seems plain wrong - add a name property to your new FileReader() instance and then access it via evt.target. Works in FF and Chrome anyway.
var input = document.getElementById('filesToUpload');
input.addEventListener("change", soWrongButItSeemsToWork, false);
function soWrongButItSeemsToWork () {
var filelist = this.files;
for (var x = 0; x < filelist.length; x++) {
oFReader = new FileReader();
oFReader.name = filelist[x].name;
console.log("name outside:", oFReader.name);
oFReader.onload = function (oFREvent ) {
imageSrc = oFREvent.target.result;
console.log('name inside:', oFREvent.target.name);
img = document.createElement("img");
img.src = imageSrc;
document.body.appendChild(img);
};
oFReader.readAsDataURL(filelist[x]);
}
}
Use a closure as suggested by http://www.htmlgoodies.com/beyond/javascript/read-text-files-using-the-javascript-filereader.html (at the bottom). Something like:
var input2 = document.getElementById('fileinput');
input2.addEventListener("change", readMultipleFiles, false);
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) { // WOOHOO!
var dataUri = e.target.result,
img = document.createElement("img");
img.src = dataUri;
document.body.appendChild(img);
console.log( "Got the file.n"
+"name: " + f.name + "\n"
+"type: " + f.type + "\n"
+"size: " + f.size + " bytes\n"
);
};
})(f);
r.readAsDataURL(f);
}
} else {
alert("Failed to load files");
}
}
Good article on MDN here https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Try this code work perfectly:
var input = document.getElementById('filesToUpload');
for (var x = 0; x < input.files.length; x++) {
oFReader = new FileReader();
oFReader.readAsDataURL(input.files[x]);
oFReader.onload = function (oFREvent) {
imageSrc = oFREvent.target.result;
console.log("source:" +imageSrc);
name = imageSrc.replace(/^.*[\\\/]/, '');
console.log("name:" +name);
};
}
I have did a work around for this and here is the example given:
var input = document.getElementById('filesToUpload');
for (var x = 0; x < input.files.length; x++) {
oFReader = new FileReader();
oFReader.readAsDataURL(input.files[x]);
var index = 0;
oFReader.onload = function (oFREvent) {
imageSrc = oFREvent.target.result;
console.log("source:" +imageSrc);
//name = oFREvent.target.name;
name = input.files[index++].name;
console.log("name:" +name);
};
}
Each time I iterate over the reader object then I increment the index so that it indexs to the next fine in the array.

Categories

Resources