开发者

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 nam开发者_StackOverflow社区e="upload" id="upload" type="file">


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.


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.


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)
    );
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜