Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 281
MintDeparture Avatar asked Jan 03 '14 15:01

MintDeparture


3 Answers

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);
like image 199
Sebastien C. Avatar answered Sep 20 '22 10:09

Sebastien C.


Here is a React version that worked for me, posting it in the event that it could save some time.

Form field

<input type="file" 
   name="file"  
   id="file" 
   multiple="multiple" 
   onChange={onChangeHandler} 
   className="fileUp" />

JSX

const onChangeHandler = event => {
    console.log(event.target.files[0].size);
}
like image 39
Michael Nelles Avatar answered Sep 21 '22 10:09

Michael Nelles


Old question but here is my take: I had the same issue but didn't want te rely on buffering to prevent my app from downloading the images twice (as the accepted answer does). What I ended up doing was fetch the file as a blob, read the file size, and use the blob as image source from there on. this was easily done with the URL.createObjectURL() function like so:

let img = new Image()
img.crossOrigin = "Anonymous"; // Helps with some cross-origin issues

fetch('foo.png')
.then(response => response.blob())
.then(blob => { img.src = URL.createObjectURL(blob); })

This looks a lot cleaner and perhaps it can still be useful for some.

like image 32
Sam Avatar answered Sep 18 '22 10:09

Sam