I'm trying to do thumbnails for the images uploaded. I want to create diferents classes for the thumbs, for this, I'm trying to use de i of the loop. But this assume just the final value. Why? Thanks
for (var i = 0; i < inp.files.length; i++) {
//create the thumbnails
var reader = new FileReader();
reader.onload = function (e) {
$('.thumbs').append('<div class="thumb_item" id="c'+ i +'"></div>');
$('<img />').attr({'src': e.target.result}).addClass('img_thumb').appendTo('.thumb_item:last');
};
reader.readAsDataURL(this.files[i]);
}
Why can't you apply the same technique pointed out in the comment?
reader.onload = (function(index)
{
return function (e)
{
$('.thumbs').append('<div class="thumb_item" id="c'+ index +'"></div>');
$('<img />').attr({'src': e.target.result}).addClass('img_thumb').appendTo('.thumb_item:last');
};
})(i);
Thanks for all, I solved this way:
for (var i = 0; i < inp.files.length; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
var count = i;
return function (e) {
$('.thumbs').append('<div class="thumb_item" id="c'+ count +'"></div>');
$('<img />').attr({'src': e.target.result}).addClass('img_thumb').appendTo('.thumb_item:last');
};
})(i);
reader.readAsDataURL(this.files[i]);
}
Related
Could anybody help me out sorting the following code or help me in the right direction?
It needs to import data from a .txt file and store it into localstorage as key & value.
Key is before ':' and value comes after it. A new key / value is separated after each ','.
Sample data from .txt file is:
nl-step1chapter1Question6:U2FsdGVkX19bRT84xShxK+29ypgj1d6ZHt+2DVBCUtY=,nl-step1chapter1Question1:U2FsdGVkX1+/Sv61L69bLvQGTkf1A9Uy4jgJ3KZTkzI=,nl-step1chapter1Question4:U2FsdGVkX1+9SVVOvTKeZuaQGj58L5WnEgL8htS0c7U=,jft:320982da-f32a-46a2-a97c-605ebe305518,nl-step1chapter1Question5:U2FsdGVkX19pi8A+PQZ7rBNCWrFeCwl2HdXpV+wWkFk=,nl-step1chapter1Question2:U2FsdGVkX19hnRnpmP3omzYNU0jXd3NtsHM+mvGYBnc=,nl-step1chapter1Question3:U2FsdGVkX1+hPbMRN+x19y7pF73eXoxG0qK1igZYZbA=
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="application/x-javascript">
$(function importData() {
document.getElementById('file').onchange = function () {
//debugger;
var file = this.files[0];
var reader = new FileReader();
reader.onload = function (progressEvent) {
//console.log(this.result.split(','));
var lines = this.result.split(',');
var list = [];
for (var line = 0; line < lines.length; line++) {
list.push(lines[line]);
localStorage.setItem([line],lines);
}
};
reader.readAsText(file);
};
});
</script>
Any help is much appreciated!
The way you are using FileReader doesn't seem correct to me. This is how your importData() function should be:
$(function importData() {
document.getElementById('file').onchange = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
var text = reader.result;
var lines = text.split(',');
for (var line = 0; line < lines.length; line++) {
let elements = lines[line].split(':');
localStorage.setItem(elements[0], elements[1]);
}
};
reader.readAsText(input.files[0]);
};
});
It will insert the elements in the localStorage as you described. For example: key = step1chapter1Question1 and value = U2FsdGVkX1+/Sv61L69bLvQGTkf1A9Uy4jgJ3KZTkzI=
I have multiple images that need to be uploaded and in preview user should be able to select one of those images for their main image.My idea was to assign them an id with counted but that doesn't seem to work,they always have the same id of number of images that are uploaded. This is js a code that I am using
$(function() {
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML("<img height=' 50px' width='50px' class='img-id' id='" +i+"'>")).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
I think the problem here is because you declared i as a global variable, so when the onload method is called it is getting the i global value which is now equal to your array size.
Fix by declaring the var properly.
$(function() {
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (var i = 0; i < filesAmount; i++) {
let index = i;
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML("<img height=' 50px' width='50px' class='img-id' id='" + index + "'>"))
.attr('src', event.target.result)
.appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
I have a mulitple input file and I will want to display the selected images in a div.
I tried with this code but it just shows me the first image
I try with this :
function readURL(input) {
var reader = new FileReader();
reader.onload = function(e) {
for (var i = 0; i <= input.files.length; i++) {
var imgId = $('<img />', {
id: 'show_bultin_paie-' + input.files[i].lastModified,
alt: 'MyAlt'
});
imgId.appendTo($('#imagediv'));
$(imgId).attr('src', e.target.result);
}
}
reader.readAsDataURL(input.files[0]);
}
}
$('#file_test').change(function(event) {
readURL(this);
});
You're not looping all the files, you're only reading the first one (reader.readAsDataURL(input.files[0]);). Use let instead of var since you're doing async stuff inside the loop.
function readURL(input) {
for (let i = 0; i < input.files.length; i++) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagediv').append("<img src='"+e.target.result+"'>");
}
reader.readAsDataURL(input.files[i]);
}
}
$('#file_test').change(function(event) {
readURL(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=file id=file_test multiple accept='image/png, image/jpg, .png, .jpg'>
<div id=imagediv></div>
I need help with making thumbnail images before uploading. I read a lot of questions here, but my problem (as I think) is a bit different.
So my code:
function nextImg(num, name){
var out = '<div class="row"><div class="col-md-2 col-xs-12" id="img_'+num+'"><img class="img-responsive pad img-thumbnail" id="imgreal_'+num+'" src="#" alt="'+name+'"></div></div>';
return out;
}
function showImgs(event){
var files = event.target.files;
if(files['length'] > 0){
var div_edit = ""
for(var i = 0; i < files['length']; i++){
div_edit += nextImg(i,files[i]['name']);
}
document.getElementById("img_container").innerHTML = div_edit;
for(var i = 0; i < files['length']; i++){
var reader = new FileReader();
console.log(i);
reader.onload = function (e) {
var num = "imgreal_"+i;
console.log(num);
var output = document.getElementById(num);
output.src = reader.result;
}
reader.readAsDataURL(event.target.files[i]);
}
}else{
document.getElementById('mainTAGs').style.display = "none";
}
}
<form role = "form" method = "post">
<div class="container col-md-12 col-xs-12" id="img_container">
</div>
</form>
So when I iterate over the opened images in the second for cycle the code gave all reader.onload function uniq "imgreal_#" id.
When onload was called I log the id and it is always the end criteria of the for cycle.
For example, let say I want to upload 3 images, then all the getElementById in the reader.onload function called with "imgreal_3" instead of "imgreal_0"... "imgreal_2".
Any suggestion how to solve it?
THX in advance! :)
This is the common gotcha for JS. To make it work you should store somewhere current iteration value for the async functions to access it later. E.g. you can store the index in IIFE:
(function() {
reader.onload = function (e) {
var num = "imgreal_"+i;
console.log(num);
var output = document.getElementById(num);
output.src = reader.result;
}
})(i)
The solution was:
(function(n) {
var reader = new FileReader();
reader.onload = function (e) {
var num = "imgreal_"+n;
console.log(num);
var output = document.getElementById(num);
output.src = reader.result;
}
reader.readAsDataURL(event.target.files[n]);
})(i);
I was wondering if it is possible to get this right. I am using a Jquery cropping tool (cropit). I am trying to put multiple file inputs into several cropper instances at once. Unfortunately it doesnt work that well.
For example, if I upload three images, the first two croppers are empty and the last one gets one of the images randomly. Here is the function:
function handleCropit(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var count = counterCropit();
var reader = new FileReader();
reader.onload= function(e){ $('#image-cropper'+count).cropit('imageSrc', e.target.result);};
reader.readAsDataURL(file);
}
}
Figured it out!
function handleCropit(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var count = counterCropit();
var croper = $('#image-cropper'+count);
var reader = new FileReader();
reader.onload= (function (yo) {return function(e){ yo.cropit('imageSrc', e.target.result);}})(croper);
reader.readAsDataURL(file);
}
}