How can I pass parameter when upload image? - javascript

My javascript code is like this :
for(var i=0; i < 5; i++) {
$('input[name="photo-'+i+'"]').change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageProducIsLoadedt;
reader.readAsDataURL(this.files[0]);
}
});
}
function imageProducIsLoadedt(e) {
$('#thumbnail-view-0').attr('src', e.target.result);
document.getElementById("thumbnail-upload-0").style.display = "none"
...
};
For example I click input file with name = photo-3, it will run loop on the index 3
Which I ask is : How do I send parameter i = 3 to imageProducIsLoadedt function?
I try add parameter like this :
reader.onload = imageProducIsLoadedt(e, i);
And the imageProducIsLoadedt like this :
function imageProducIsLoadedt(e,i) {
But, there exist error like this :
Uncaught ReferenceError: e is not defined
How can I solve this problem?
UPDATE
I try to update global variable like this :
let test = '';
for(let i=0; i < 5; i++) {
$('input[name="photo-'+i+'"]').change(function () {
test = i;
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageProducIsLoadedt;
reader.readAsDataURL(this.files[0]);
}
});
}
function imageProducIsLoadedt(e) {
console.log(test)
...
};
It works

You can create an anonymous function with register onload and inside that call your imageProducIsLoadedt function like below
for(var i=0; i < 5; i++) {
$('input[name="photo-'+i+'"]').change(function (e) {
if (this.files && this.files[0]) {
var reader = new FileReader();
(function(i){
reader.onload = function(){
imageProducIsLoadedt(e,i);
}
});
reader.readAsDataURL(this.files[0]);
}
});
}

Related

Javascript variable not changing inside onload function

this code always return me '3' in alert.
I select two files together (ones .mp4 format and second ones .zip format)
function readFile(input) {
var counter = input.files.length;
for(x = 0; x<counter; x++){
if (input.files && input.files[x]) {
var extension = input.files[x].name.split('.').pop().toLowerCase();
var reader = new FileReader();
reader.onload = function (e) {
urlss = 1;
if(extension == 'mp4'){
urlss = 2;
}else{
urlss = 3;
}
alert(urlss);
};
reader.readAsDataURL(input.files[x]);
}
}
}
<input type="file" id="files" name="files[]" accept=".png, .jpg, .jpeg, .zip, .mp4" onchange="readFile(this);" multiple />
That is because of var hoisting
The onload function calling after the for was ended and extension == last file extension
Try replace var with const:
function readFile(input) {
var counter = input.files.length;
for(let x = 0; x < counter; x++){
if (input.files && input.files[x]) {
const extension = input.files[x].name.split('.').pop().toLowerCase();
const reader = new FileReader();
reader.onload = function (e) {
urlss = 1;
if(extension == 'mp4'){
urlss = 2;
}else{
urlss = 3;
}
alert(urlss);
};
reader.readAsDataURL(input.files[x]);
}
}
}
Update
Please check the Webber's comment below.

JQuery FileReader onload not firing

I have a multiple file uploading. When I upload the images and binding to the model as follows not firing the FileReader onload function. It skip and fire remain
Here is my code
imageSelect: function (e) {
var dataModel = bindViewModel.selected.attachments;
var reader = new FileReader();
reader.onload = function () {
var uploadImg = new Image();
uploadImg.onload = function () {
for (var i = 0; i < e.files.length; i++) {
if (e.files[i].size < 1048576) {
var attachmentName = e.files[i].name;
var attachment = { id: i, citationId: bindViewModel.selected.id, attachmentName: attachmentName, attachmentUrl: reader.result };
dataModel.push(attachment);
if (dataModel[0].attachmentName == "" && dataModel[0].attachmentUrl == "") {
dataModel.splice($.inArray(dataModel[0], dataModel), 1);
}
uploadImg.src = reader.result;
reader.readAsDataURL(e.files[i].rawFile);
}
else {
app.ShowNotifications("Error", 'The ' + e.files[i].name + ' size greater than 1MB. \r\n Maximum allowed file size is 1MB.', "error");
}
}
};
};
}
Any one can have to help me?

Why does my redirect is not working?

my script calls my redirect function to early, so the last file of a batch upload is failing. I have been search the whole morning an tried different approaches, but without success.
function uploadFile(something, callback) {
var fileInput = $('#fileList1');
//var reader = new FileReader();
console.log(fileInput);
if ( trim( fileInput.val() ).length == 0 ) {
return;
}
var fileList = [];
count = fileInput[0].files.length;
for(i = 0; i < count; i++){
loadFile(fileInput[0].files[i]);
}
function loadFile(file){
var reader = new FileReader();
var fileName = getFileNameWithExtension( file);
var file = file;
while(reader.onprogress){
console.log("reading");
}
reader.onload = function(event) {
var val = reader.result;
var text = val.split(',')[1];
saveFile( fileName, text, parentId );
if (!--count){
redirect();
}
}
reader.onerror = function(event) {
console.error("File could not be read! Code " + reader.error.message);
}
reader.readAsDataURL(file);
}
}
function redirect(){
window.location.href = '/{!tempID}';
return false;
}
Can someone give me a hint?
#
Hello, i have rewritten my methods a bit based on your suggestions. But the redirect is still called to early,...before all uploads are done.
function uploadFile() {
var fileInput = $('#fileList1');
console.log(fileInput);
if ( trim( fileInput.val() ).length == 0 ) {
return;
}
var countTwo = 0;
count = fileInput[0].files.length;
for(var i = 0; i < count; i++){
loadFile(fileInput[0].files[i], function(val){
console.log(val);
if(val === 3){
setTimeout(()=>{redirect();}, 5000);
}
});
}
function loadFile(file, callback){
var reader = new FileReader();
var fileName = getFileNameWithExtension( file);
var file = file;
while(reader.onprogress){
console.log("reading");
}
reader.onload = function(event) {
var val = reader.result;
var text = val.split(',')[1];
saveFile( fileName, text, parentId );
console.log(" ct " + countTwo + " c " + count-1);
countTwo++;
if(!--count) callback(countTwo);
}
reader.onerror = function(event) {
console.error("File could not be read! Code " + reader.error.message);
}
reader.readAsDataURL(file);
}
}
Method 1: (Recommended)
Detect when your uploading ends. And in that callback, call redirect.
Method 2:
// define your TIMEOUT first
setTimeout(()=>{redirect();}, TIMEOUT);
reader.onload = function(event) {
var val = reader.result;
var text = val.split(',')[1];
saveFile( fileName, text, parentId );
if (!--count){
setTimeout(()=>{redirect();}, 0);
}
}

Unable to pass a variable to a function

I want to pass the current index to a function reading images via FileApi and showing preview of them:
for(var i = 0, f; f = files[i]; i++) {
if (!f.type.match("image.*")) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var dv = document.createElement("div");
//.............
};
})(f);
reader.readAsDataURL(f);
}
I've tried this:
//.......
var reader = new FileReader();
reader.onload = (function(theFile, i2) {
//i2 is defined here
return function(e) {
var dv = document.createElement("div");
//i2 isn't defined here
};
})(f, i);
But as you can see, i2 isn't defined. How to fix that?
If you organize the wrapper function(s) a bit, everything can be properly scoped. Here I wrap basically the whole loop body in a self-calling function. The onload handler is then just a plain old function assignment. In your production code you can remove the dummy onload.
var files = ['one', 'two', 'three'];
for (var i = 0, f; f = files[i]; i++) {
(function(i, f) {
var reader = new FileReader();
reader.onload = function() {
var dv = document.createElement("div");
console.log(f + i);
};
// dummy onload
(function(r) {
setTimeout(r.onload, 1000 + (i + 1) * 333);
})(reader);
})(i, f)
}

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"));

Categories

Resources