onload function in javascript not working Android - javascript

I am trying to read a image as a file and then display the image name,size etc. I debugged my code and found my onload function is loading but not working. Thank you for your help. I have included my whole FileSelection() method.
var iBytesUploaded = 0;
var iBytesTotal = 0;
var iPreviousBytesLoaded = 0;
var iMaxFilesize = 1048576; // 1MB
var oTimer = 0;
var sResultFileSize = '';
var oImage = new Image();
function fileSelected() {
alert("hello");
// hide different warnings
document.getElementById('upload_response').style.display = 'none';
document.getElementById('error').style.display = 'none';
document.getElementById('error2').style.display = 'none';
document.getElementById('abort').style.display = 'none';
document.getElementById('warnsize').style.display = 'none';
// get selected file element
var oFile = document.getElementById('image_file').files[0];
// filter for image files
var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
if (! rFilter.test(oFile.type)) {
alert("problem");
document.getElementById('error').style.display = 'block';
return;
}
// little test for filesize
if (oFile.size > iMaxFilesize) {
document.getElementById('warnsize').style.display = 'block';
return;
}
// get preview element
oImage = document.getElementById('preview');
alert("hello2");
// prepare HTML5 FileReader
var oReader = new FileReader();
alert("hello3")
oReader.onload = function(e)
{
alert("hello4");
alert("reached");
oImage.onload = function () { // binding onload event
alert("hi");
// oImage.src = e.target.result;
// we are going to display some custom image information here
sResultFileSize = bytesToSize(oFile.size);
document.getElementById('fileinfo').style.display = 'block';
document.getElementById('filename').innerHTML = 'Name: ' + oFile.name;
document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
};
// e.target.result contains the DataURL which we will use as a source of the image
oImage.src = e.target.result;
};
alert("file found");
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}

Giving you the changes I was talking about in the comments:
//You want this somewhere
var oImage = new Image();
var oReader = new FileReader();
alert("hello3")
oReader.onload = function(e)
{
alert("hello4");
oImage.onload = function () { // binding onload event
alert("hi");
// we are going to display some custom image information here
sResultFileSize = bytesToSize(oFile.size);
document.getElementById('fileinfo').style.display = 'block';
document.getElementById('filename').innerHTML = 'Name: ' + oFile.name;
document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
};
// Make sure this comes after
oImage.src = e.target.result;
};
// read selected file as DataURL
oReader.readAsDataURL(oFile);

Related

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?

ajax listener for file uploading progress

I cant find a way to get around my code. I have seen some tutorials out there, but because of the way I design my code I guess I need something different.
(function(){
var dropzone = document.getElementById('dropzone');
var uploadFile = function (files) {
var formData = new FormData();
var request = new XMLHttpRequest();
var i;
var file_size = 0;
for(i = 0; i<files.length; i = i+1){
formData.append('file[]', files[i]);
file_size = file_size + files[i].size;
}
request.onload = function(){
var data = this.responseText;
// window.location.reload();
};
request.open('post', 'dragNdrop.php?isNotSet=set');
request.send(formData);
};
dropzone.ondragover = function(){
this.className = 'dropzone dragover';
return false;
};
dropzone.ondragleave = function(){
this.className = 'dropzone';
return false;
};
dropzone.ondrop = function (event) {
event.preventDefault();
this.className = 'dropzone';
uploadFile(event.dataTransfer.files);
return false;
}
}());
This is the code I use to upload a file, but i cant find a way to add a eventlistener that keeps checking if the file has been uploaded. I have tried.
request.upload = function(){console.log("me")} //Returns nothing
I tried something like this:
request.upload.addEventListener("progress", progressBar, false);
function progressBar(event){
var percent = (event.loaded / event.total) * 100;
console.log(percent + " " + event.loaded + " " + event.total);
}
It only returns the value once, I would imagine it needs to return several times as it needs to loop in order to get the progress bar moving?
All this function below was inside the main function.
How else could I do this?

Async checking image width and height and if they are OK, preview image

I'm trying to check width and height from an input file's images and check if they are at least equal than specific dimension (w:300px, h:300px).
I have this check:
window.onload = function () {
var fileUpload = document.getElementById("inputFileID");
fileUpload.onchange = function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = document.getElementById("divToShowThumbs");
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for (var i = 0; i < fileUpload.files.length; i++) {
var file = fileUpload.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.src = e.target.result;
dvPreview.appendChild(img);
}
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
}
};
This works ok to preview each image.
But when I try to use "IF - ELSE" using img.width, it returns 0 because it works in asynchronous way!
Any light about how can I solve this situation?
All I'm trying to do is read each image, check if they area 300px (height and width) and if Ok, create the preview!
I got help from this - Getting width & height of an image with filereader . And here is your modified script.
window.onload = function () {
var fileUpload = document.getElementById("inputFileID");
fileUpload.onchange = function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = document.getElementById("divToShowThumbs");
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for (var i = 0; i < fileUpload.files.length; i++) {
var file = fileUpload.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.src = e.target.result;
img.onload = function() {
// access image size here
console.log(this.width + " " + this.height);
if(this.width <=300 && this.height <=300 ) {
dvPreview.appendChild(img);
}
else {
alert("too big an image!");
}
};
};
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
};
};

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.

How to detect if the image path is valid?

I have found a question regarding the images
How to detect if the image path is broken?
I have tried the following codes
var image = new Image;
image.src = "http://project" + path + '.png';
image.onload = function(){
var imageWidth = this.width + this.height;
if(imageWidth==0){
image.src = "http://project2" + path + '.png';
//the project2 path could be broken too and
//I want to use project3 or project4 as the
//path and keep testing it, but there is no way to do it from here.
}
}
Would it be possible to do a recursive test here? Thanks a lot!
You could try this setup:
var paths = ["/img1", "/img2", "/img3"];
var beginning = "http://project";
var ending = ".png";
function getImage(images, prefix, suffix, callback) {
var iterator = function (i) {
if (i < images.length) {
var image = new Image();
image.onload = function () {
var imageWidth = this.width + this.height;
if (imageWidth === 0) {
console.log("onload problem");
iterator(++i);
} else {
console.log("onload good");
callback(i, image);
}
};
image.onerror = function () {
console.log("onerror");
iterator(++i);
};
image.src = prefix + images[i] + suffix;
}
};
iterator(0);
}
getImage(paths, beginning, ending, function (index, img) {
console.log("Callback: ", index, ", ", img);
});
DEMO: http://jsfiddle.net/2mRMr/2/
Broken images would call onerror, not onload.
image.onerror = function () {
console.log("broken");
callToTryNewSrc();
}
Basic recursive check
function getImage(path, callback) {
//if numeric
var ind = 1;
var maxServer = 5;
//if named differently
//var ind = 0;
//var servers = ["//foo1","//foo2","//bar1"];
//var maxServer = servers.length-1;
function test() {
var img = new Image();
img.onload = function () {
if (callback) {
callback(img);
}
}
img.onerror = function () {
if (ind <= maxServer) {
test();
} else {
if (callback) {
callback(img);
}
}
}
var currentPath = "http://project" + ind + path + '.png';
//var currentPath = servers[ind] + path + '.png';
img.src = currentPath;
ind++;
}
test();
}
//calling it
getImage("/foo", function (img) {
console.log(img);
});

Categories

Resources