Frage

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.

War es hilfreich?

Lösung

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

Andere Tipps

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);
}

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.

Assuming you could use HTML5

  1. Create a canvas
  2. Put image in there
  3. Grab the image data with .toDataURLHD()
  4. Grab the base64 encoded string
  5. Use some mad calculation to get the image size in bytes.

Have fun!

Maybe it's a lot easier to use a server side script, so it won't be HTML5-dependant

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top