Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you determine the file size in JavaScript?

I help moderate a forum online, and on this forum we restrict the size of signatures. At the moment we test this via a simple Greasemonkey script I wrote; we wrap all signatures with a <div>, the script looks for them, and then measures the div's height and width.

All the script does right now is make sure the signature resides in a particular height/width. I would like to start measuring the file size of the images inside of a signature automatically so that the script can automatically flag users who are including huge images in their signature. However, I can't seem to find a way to measure the size of images loaded on the page. I've searched and found a property special to IE (element.fileSize) but I obviously can't use that in my Greasemonkey script.

Is there a way to find out the file size of an image in Firefox via JavaScript?

Edit: People are misinterpreting the problem. The forums themselves do not host images; we host the BBCode that people enter as their signature. So, for example, people enter this:

This is my signature, check out my [url=http://google.com]awesome website[/url]!
This image is cool!  [img]http://image.gif[/img]

I want to be able to check on these images via Greasemonkey. I could write a batch script to scan all of these instead, but I'm just wondering if there's a way to augment my current script.

like image 738
Dan Lew Avatar asked Jul 14 '09 17:07

Dan Lew


2 Answers

As you know IE supports the fileSize property of an image. No such luck in other browsers ... however, you should be able to modify this script:

http://natbat.net/2008/Aug/27/addSizes/

It uses JSON to read HTTP headers of files and display their actual file size. That should help you prevent people uploading large animated GIFs.

As for getting the dimensions:

var img = new Image();
theImage.src = "someimage.jpg";
actualwidth = theImage.width;
actualheight = theImage.height;

This of course is a pure client-side approach to something best handled server-side.

like image 54
Keith Adler Avatar answered Oct 06 '22 06:10

Keith Adler


Actually, with HTML5, this is now possible,
read more information here.

like image 43
funerr Avatar answered Oct 06 '22 06:10

funerr