我试图正常上传图像使用HTML和JS,但我想在上传图像之前验证那里的像素,如果图像有合适的像素,那么它应该添加到DOM,否则没有
这是我的HTML代码
<!DOCTYPE html>
<html>
<head>
<title>Img Upload</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<section>
<div class="container">
<p>Hello</p>
<input type='file' />
<br>
<img id="myImg" src="#" alt="Upload Image" height=200 width=200>
</div>
</section>
</body>
<!-- Js File -->
<script type="text/javascript" src="D:\Practice\imgUpload\script.js"></script>
</html>下面是我的JS代码
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
var img = document.querySelector('img'); // $('img')[0]
img.src = URL.createObjectURL(this.files[0]); // set src to blob url
img.onload = function() {
// var width = img.naturalWidth,
// height = img.naturalHeight;
// window.URL.revokeObjectURL( img.src );
var width = img.width;
var height = img.height;
if( width == 100 && height == 100 ) {
imageIsLoaded;
}
else {
alert ("add proper pixel image");
}
};
}
});
});
function imageIsLoaded() {
alert(this.src); // blob url
// update width and height ...
}在尝试上面的代码后,它会警告您的图像不在正确的像素中,但在警告框关闭后,图像会被上传。简单:如果像素匹配,我想添加一个图像,否则它不会添加到DOM上
发布于 2020-03-20 22:11:47
你的代码有几个问题:
img.naturalWidth和img.naturalHeight。img.width和img.height根据您的标记返回图像的大小:在本例中,它是200,这是不正确的。当调用函数imageIsLoaded()你需要访问函数中的
imageIsLoaded(img)。然后,在函数声明中执行function imageIsLoaded(img),以便在函数范围内可以访问上传的图像。要控制图像的显示/隐藏,只需在默认情况下将其设置为display: none,然后在imageIsLoaded()函数中将其设置为display: block。
如下例所示:
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
var img = document.querySelector('img'); // $('img')[0]
img.src = URL.createObjectURL(this.files[0]); // set src to blob url
img.onload = function() {
var width = img.naturalWidth;
var height = img.naturalHeight;
if (width == 100 && height == 100) {
imageIsLoaded(img);
} else {
console.log("add proper pixel image");
img.style.display = 'none';
}
};
}
});
});
function imageIsLoaded(img) {
img.style.display = 'block';
console.log(img.src);
}<div class="container">
<p>Hello</p>
<input type='file' />
<br>
<img id="myImg" src="" alt="Upload Image" height="200" width="200" style="display: none;">
</div>
https://stackoverflow.com/questions/60775723
复制相似问题