Skip to content
Advertisement

How do you get the file size of an image on the web page with Javascript?

I’d like to be able to get the file size on an image on a webpage.

So let’s say I have an image on the page (that has loaded) like this:

How do I call a function in Javascript (or, even better, jquery) to get the file size (not the dimensions) of the image?

It’s important to note that I’m not using any inputs or having users upload the image, there’s lots of SO answers on getting image sizes from browse buttons with the file API.

All I want to do is get the file size of any arbitrary image on the page based of it’s id and src url.

Edit: I’m dealing with a keep-alive connection for some images so the Content-Length headers are not available.

Advertisement

Answer

You can’t directly get the file size (or any data from it).

The only way is a bit dirty, because you have to do a XMLHTTPRequest (and it probably won’t work with externals images, according to the “Cross Origin Resource Sharing”). But with the browser’s cache, it should not cause another HTTP request.

var xhr = new XMLHttpRequest();
xhr.open("GET", "foo.png", true);
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function() {
    if(this.readyState == this.DONE) {
        alert("Image size = " + this.response.byteLength + " bytes.");
    }
};
xhr.send(null);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement