admin管理员组

文章数量:1405576

I am trying to validate the image uploaded by the user. So, after the user adds its image, before uploading it on the server, I tried validating the image dimensions with the javascript code below but it won't work.

function check_image_dimensions(){
var t=document.getElementById("main_file_1");
e=t.clientWidth;

n="";
o="We could not upload your image because \n \n";
if (e<300) {
(n+="The height of the image must be greater than 300px \n";
}
if(i<300){
n+="The height of the image must be greater than 300px \n";
}

I also tried:

e=t.width;
i=t.height;

But it still doesn't work. What am I doing wrong?

Thank you!

I am trying to validate the image uploaded by the user. So, after the user adds its image, before uploading it on the server, I tried validating the image dimensions with the javascript code below but it won't work.

function check_image_dimensions(){
var t=document.getElementById("main_file_1");
e=t.clientWidth;

n="";
o="We could not upload your image because \n \n";
if (e<300) {
(n+="The height of the image must be greater than 300px \n";
}
if(i<300){
n+="The height of the image must be greater than 300px \n";
}

I also tried:

e=t.width;
i=t.height;

But it still doesn't work. What am I doing wrong?

Thank you!

Share Improve this question asked Nov 6, 2013 at 23:10 user2961763user2961763 631 silver badge9 bronze badges 2
  • 1 What is main_file_1, an img tag, or the file input tag? – varfoo Commented Nov 6, 2013 at 23:16
  • It's the id I gave to the image. I have: <input type="file" id="main_file_1" name="main_file_1"> – user2961763 Commented Nov 6, 2013 at 23:23
Add a ment  | 

1 Answer 1

Reset to default 8

Something like:

1) Put the image in a hidden <img/> element

See this example: MDN - Using files from web applications

2) Check the size (bounding box) of the <img/> element

if(img.getBoundingClientRect().width<300) ...

3) Alert the user (or not)

Here is a working version: JSFiddle.

Browser Compatability: Firefox 3.6+, Chrome 7+, IE 10+, Opera 12+

本文标签: javascriptPicture height and width before uploadingStack Overflow