Here is a jquery script which triggers after a user select a file for upload (the code is a little messy for debugging).
1. After user selects a jpeg image file (f), then the image is loaded and its width and height are compared against the max allowed.
2. If image is too large, then call resize to size down.
3. Since image onload is asynchronous, a callback function afterloading(image) is called:
$(function(){
$('#uploaded_file_file_for_upload').change(function(){
var _URL = window.URL || window.webkitURL;
var img;
var max_width = 0;
var max_height = 0;
var max_size_mb;
var f = $(this)[0].files[0];
if (f != null) {
max_width = $('#max_width').val();
max_height = $('#max_height').val();
max_size_mb = $('#max_size_mb').val();
alert(max_width +', ' + max_height);
$('#file_name').val(f.name);
alert(f.name);
$('#file_size').val(f.size/1024);
$('#file_type').val(f.type); //image/jpeg
$('#file_extension').val(f.name.split('.').pop().toLowerCase());
alert(f.type);
alert(f.name.split('.').pop().toLowerCase());
if (f.type == 'image/jpeg') {
img = new Image();
img.onload = function () {
afterloading(this);
return false;
};
img.src = _URL.createObjectURL(f);
};
};
function afterloading(image) {
var w = image.width, h = image.height;
alert('hi-max' + max_width + ' -- ' + max_height);
alert('hi' + w + ' xx ' + h);
if (w > max_width || h > max_height) { img.src = _URL.createObjectURL(f);
if (w > max_width){
h = Math.ceil(h * max_width / w);
w = max_width;
} else if (h > max_height) {
w = Math.ceil(w * max_height / h);
h = max_height;
};
alert('before resize, ' + w + ' ?? ' + h );
resize(image, w, h);
$('#remove').val('true');
return false;
};
};
function resize(image, width, height) {
alert('resize');
var mainCanvas = document.createElement("canvas");
mainCanvas.width = width;
mainCanvas.height = height;
var ctx = mainCanvas.getContext("2d");
ctx.drawImage(image, 0, 0, width, height);
$('#uploaded_file_hidden_file').val(mainCanvas.toDataURL("image/jpeg"));
$('#file_size').val(image.size/1024);
alert($('#file_size').val());
alert("++" + image.size);
return false;
};
return false;
});
});
The problem is that the execution of afterloading(image) causes infinite loop. What could cause the infinite loop?
UPDATE:
There is the same infinite loop after commenting out the resize(image, w,h) in afterloading. So the problem is within afterloading itself.
Gabe Moothart, the.changeis on another id offile_for_uploadand is not onhidden_file.