简体   繁体   中英

How to get size of an image in javascript?

在PHP中有filesize() ,而在javascript中呢?

You can't do it in javascript.

You could send an asynchronous message to a PHP function getting the size and then display it using javascript, but there is no full JS way of doing it.

The best you can do is to tell the user only images smaller than X bytes will be accepted. You can't stop him from uploading an image smaller than the max upload size defined in your php.ini.

Get the image, then server-side, in PHP, check the size and display an error message if it's too big.


Of course, you can use AJAX. If you want, use an AJAX upload control like this one . The checking will still be done server-side but your page will feel more interactive and agile.

You could use a Flash Uploader to get the filesize before anything is sent to the server. For example the jquery plugin (like uplodify.com) or the YUI Uploader . But in any case you should check on the php side again by checking the POST array $_FILES

When the upload starts, the browser will send the image file size to the server as part of the HTTP header. So you can check the size before more than a few KB of the image were transferred and abort the upload. Note that the size is not exact since the data can be encoded for the transfer, so the size is probably too large.

No server side needed:

Add an empty div to the page with padding:0 and display:"inline" ("inline" needed so the width collapses). Using jQuery or another js framework, drop the image into the div . The div will resize to fit the image. jQuery will return the correct width/height of the div which is the width/height of the image.

Using javascript alone won't work because js won't return a width/height unless it's set to a fixed value in the style.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM