我有一个用于将图像上传到服务器的上传控件,但在上传之前我只想确保图像的尺寸是否正确。 在客户端有什么可以用 JavaScript 完成的吗?
最佳答案
您可以在提交表单之前检查它们:
window.URL = window.URL || window.webkitURL;
$("form").submit( function( e ) {
var form = this;
e.preventDefault(); //Stop the submit for now
//Replace with your selector to find the file input in your form
var fileInput = $(this).find("input[type=file]")[0],
file = fileInput.files && fileInput.files[0];
if( file ) {
var img = new Image();
img.src = window.URL.createObjectURL( file );
img.onload = function() {
var width = img.naturalWidth,
height = img.naturalHeight;
window.URL.revokeObjectURL( img.src );
if( width == 400 && height == 300 ) {
form.submit();
}
else {
//fail
}
};
}
else { //No file was input or browser doesn't support client side reading
form.submit();
}
});
这仅适用于现代浏览器,因此您仍然需要在服务器端检查尺寸。你也不能相信 客户端,所以这是您无论如何都必须在服务器端检查它们的另一个原因。
关于javascript - 是否可以在上传前检查图像尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57384302/