我知道这可能需要一些 javascript,但我如何告诉表单中的输入拒绝尺寸不同于 64 x 64 的图像而不按提交按钮。
<div class="form-group">
<label for="plat_img">Icono</label>
<input type="file"
accept="image/*"
class="form-control"
id="plat_img">
验证应在选择图像后立即进行,如果被拒绝,则通过警报通知用户。
最佳答案
这应该可以完成工作,您现在也可以添加一个好的错误消息。
var fileInput = document.getElementById("plat_img");
// listening on when someone selects a file
fileInput .onchange = function(e) {
e.preventDefault();
// get the file someone selected
var file = fileInput.files && fileInput.files[0];
// create an image element with that selected file
var img = new Image();
img.src = window.URL.createObjectURL(file);
// as soon as the image has been loaded
img.onload = function() {
var width = img.naturalWidth,
height = img.naturalHeight;
// unload it
window.URL.revokeObjectURL(img.src);
// check its dimensions
if (width <= 64 && height <= 64) {
// it fits
} else {
// it doesn't fit, unset the value
// post an error
fileInput.value = ""
alert("only 64x64 images")
}
};
};
关于javascript - HTML 文件输入接受特定尺寸的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42380031/