使用Javascript上传前请检查图片宽度和高度 [英] Check image width and height before upload with Javascript
问题描述
< div class =photo >
< div>照片(最大240x240和100 kb):< / div>
< input type =filename =photoid =photoInputonchange =checkPhoto(this)/>
< / div>
我写了这个js:
function checkPhoto(target){
if(target.files [0] .type.indexOf(image)== -1){
document.getElementById photoLabel)。innerHTML =文件不支持;
返回false;
if(target.files [0] .size> 102400){
document.getElementById(photoLabel)。innerHTML =图片太大(最大100kb);
返回false;
}
document.getElementById(photoLabel)。innerHTML =;
返回true;
}
这可以很好地检查文件类型和大小。现在我想检查图像的宽度和高度,但我不能做到这一点。
我已经尝试使用 target.files [0] .width
但我得到未定义
。用其他方法,我得到 0
。
任何建议?
文件只是一个文件,你需要像这样创建一个图像:
var _URL = window.URL || window.webkitURL; ((file = this.files [0])){
(#file)。change(function(e){
var file,img;
img = new Image();
img.onload = function(){
alert(this.width ++ this.height);
};
img.src = _URL.createObjectURL(file);
}
});
演示: http://jsfiddle.net/4N6D9/1/
我认为这只是在少数浏览器中支持的。主要是firefox和chrome,现在也可能是歌剧。
I have a JPS with a form in which a user can put an image:
<div class="photo">
<div>Photo (max 240x240 and 100 kb):</div>
<input type="file" name="photo" id="photoInput" onchange="checkPhoto(this)"/>
</div>
I have written this js:
function checkPhoto(target) {
if(target.files[0].type.indexOf("image") == -1) {
document.getElementById("photoLabel").innerHTML = "File not supported";
return false;
}
if(target.files[0].size > 102400) {
document.getElementById("photoLabel").innerHTML = "Image too big (max 100kb)";
return false;
}
document.getElementById("photoLabel").innerHTML = "";
return true;
}
which works fine to check file type and size. Now I want to check image width and height but I cannot do it.
I have tried with target.files[0].width
but I get undefined
. With other ways I get 0
.
Any suggestions?
The file is just a file, you need to create an image like so:
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
alert(this.width + " " + this.height);
};
img.src = _URL.createObjectURL(file);
}
});
Demo: http://jsfiddle.net/4N6D9/1/
I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.
这篇关于使用Javascript上传前请检查图片宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!