zmol
zmol

Reputation: 2904

Why this code isn't giving me correct dimensions of image about to be uploaded

I have an upload form for an image. When user selects a file, I need to get the image width and height with js/jquery on the client side before upload.

I'm using this code to monitor when the user selects the image they want to upload from their local computer

$('#upload').change(function(){
   if($(this).val() != null){
      getImgSize(this);         
   }
});

and it calls this function, but it alerts that the width and height are 0

function getImgSize(imgSrc){
  var newImg = new Image();
  newImg.src = imgSrc;
  var height = newImg.height;
  var width = newImg.width;
  alert ('The image size is '+width+'*'+height);
}

and this is the html markup

<input name="upload" id="upload" type="file">

Upvotes: 1

Views: 251

Answers (3)

000
000

Reputation: 280

Its not possible you trying. Its like @inti says you cant access client data information in client side script languages. The File API follow this rules as well, because the security reason is important.

A possible option is to use a server side script & ajax. With PHP & JQuery

You can use for example this uploader: http://github.com/valums/file-uploader

And a little PHP Script like this:

<?

    // use getimagesize to get image information
    list($width, $height, $type, $attr) = getimagesize($_FILES['YOURFILE']);
    json_encode(
        array('width' => $width),
        array('height' => $height)
    );
?>

Upvotes: 1

Blair McMillan
Blair McMillan

Reputation: 5349

It might be possible using the new HTML5 File API, but I'm not sure if that returns the info that you need. It's not supported very well in most browsers currently either. In short, you can't do it until the file ends up on your server for you to read.

Upvotes: 1

aorcsik
aorcsik

Reputation: 15552

There is a rule, that a client side javascript code cannot reach out to the clients file system. Because of this, you cannot get the full path of the selected file, from the input. It would only return the name of the file, which is not enough for your plan to work.

Upvotes: 4

Related Questions