gpt4 book ai didi

javascript - 图像客户端的尺寸验证

转载 作者:行者123 更新时间:2023-11-30 10:15:06 26 4
gpt4 key购买 nike

我正在处理的网站有上传图片的选项,但我必须在上传到服务器端或提交之前验证图片的尺寸(宽度、高度)。

例如,图片必须是 250x250,否则会出现警告,用户无法上传图片,这是我的部分代码:

<form action="upload_file.php" method="post"  enctype="multipart/form-data" name = "upload" id="insertBook" onSubmit="return validateImage();"> 
<input type="file" name="image" value="upload" id = "myImg">
<input type="submit" name = "submit">
</form>

validateImage 函数现在只检查扩展,我希望它也检查尺寸。

这是目前的代码:

function validateImage(){
var allowedExtension = ["jpg","jpeg","gif","png","bmp"];
var fileExtension = document.getElementById('myImg').value.split('.').pop().toLowerCase();
var isValidFile = false;
for(var index in allowedExtension) {
if(fileExtension === allowedExtension[index]) {
isValidFile = true;
break;
}
}
if(!isValidFile) {
alert('Allowed Extensions are : *.' + allowedExtension.join(', *.'));
}
return isValidFile;
}

谢谢! :)

最佳答案

function validateImage(){
var isValidFile = false;
var image = document.getElementById('myImg');

var allowedExtension = ["jpg","jpeg","gif","png","bmp"];

var srcChunks = image.src.split( '.' );
var fileExtension = srcChunks[ srcChunks.length - 1 ].toLowerCase();

if ( image.width !== image.height !== 250 ) {
console.log( 'Size check failed' );
return false;
}

for(var index in allowedExtension) {
if(fileExtension === allowedExtension[index]) {
isValidFile = true;
break;
}
}

if(!isValidFile) {
alert('Allowed Extensions are : *.' + allowedExtension.join(', *.'));
}

return isValidFile;
}

关于javascript - 图像客户端的尺寸验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24303828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com