我正在测试逐行调整大小并在窗体客户端上传文件。 有一个用于选择文件的按钮,javascript会抛出有关图像属性的警报,调整图像大小,将其分配给隐藏字段并发布表单。我从一张图片开始,相关的代码是:
HTML
<form action="add2.php" method="post" enctype="multipart/form-data" id="addform">
<input type="file" id="i1_file" onchange="resize('i1_file', 'addform')" />
<input type="hidden" name="uploadfile" id="image1" value="" />
Javascript
function resize(inputid, formid)
{
var inpFiles = document.getElementById(inputid);
var file = inpFiles.files[0];
... Initial file checks here: type, size etc...
var dataurl = null;
// create <img> element
var img = document.createElement("img");
var reader = new FileReader();
var image = document.getElementById('image1');
// document.write("Before image1 :" + image.name + "<br />");
reader.onloadend = function(e) {
img.src = e.target.result;
img.onload = function() {
// Once you have the image preview in an <img> element, you can draw this image in a <canvas> element to pre-process the file.
var canvas = document.createElement("canvas");
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var width = img.width;
var height = img.height;
//document.write("src " + img.src + "<br />");
document.write("width " + img.width + "<br />");
document.write("height " + img.height + "<br />");
if ((width > 1024) && (width > height))
{
var new_width = 1024;
var ratio = new_width / width;
var new_height = Math.round(height * ratio);
}
else if (height > 768)
{
var new_height = 768;
var ratio = new_height / height;
var new_width = Math.round(width * ratio);
}
else
{
var new_width = width;
var new_height = height;
}
document.write("new_height: " + new_height + "<br />");
canvas.width = new_width;
canvas.height = new_height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img,0,0,new_width, new_height);
// save canvas as dataUrl
dataurl = canvas.toDataURL("image/jpeg", 0.8);
document.write("FormData " + formid + "<br />");
//document.write("dataurl: " + dataurl + "<br />");
image.value = dataurl;
//var fd = new FormData(document.getElementById(formid));
document.write("Before FormData " + "<br />");
var fd = new FormData(document.forms["addform"]);
var xhr = new XMLHttpRequest();
document.write("Posting <br />" + xhr.readyState );
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// OK
alert('response:'+xhr.responseText);
// here you can use the result (xhr.responseText)
} else {
// not OK
alert('failure!');
}
}
};
xhr.open('POST', 'add2.php', true);
document.write("After Open <br />" + xhr.readyState);
xhr.setRequestHeader("Content-type","multipart/form-data");
document.write("Before Send <br />" );
xhr.send(fd);
console.log(xhr.response);
} //onload
}
reader.readAsDataURL(file);
}
第一个浏览器是Firefox,它在产生此输出后挂起(即最多xhr.open): 宽度4176 身高3120 new_height:765 FormData addform 在FormData之前 发帖 0
Chrome根本没有重定向,而是停留在表单所在的同一页面上。
IE10仅输出&#34;宽度4176&#34; (第一次调试打印)。
任何人都可以发现我做错了什么以及为什么现代浏览器中的行为如此不同?