1

say I have an image hosted externally, say on imgur, then on my site in my html I can have:
<img src="https://i.imgur.com/hDEXSt7.jpg">
and it shows the image. Even though the image is hosted externally, it's not a CORS violation to do that.

Now, before I load/display that image, I want to first check it's filesize.

On the backend, I can do this no problem with a HEAD request to the URL. But if I try to send an AJAX HEAD request from the FE, it's blocked as a CORS violation. Which makes sense, I know you generally can't do AJAX requests to external sites, for good reason.

But it seems awfully silly that with JS I can generate the HTML for displaying the image and insert that into the page such that it then must then make a call to an external website to get the image data, but I can't just ask how much data is there. Surely there must be a way.

This: https://stackoverflow.com/questions/6575159/get-image-dimensions-with-javascript-before-image-has-fully-loaded\ is pretty close to what I want, but it's for the dimensions of the image. I want the filesize. <img> elements don't seem to have a property for that. Also that seems like a weird hack where you start loading the image and get its info before it's finished. Ideally I'd like to get the filesize info before I start loading, so I can use it to decide whether or not to load the image.

I can do this by making the HEAD request from my own backend, but I'd rather not. The information I want isn't even on my backend. That just feels like such a silly waste of a call to my server just to get around the CORS restriction, given that CORS isn't going to stop me from actually going ahead and loading the whole image.

Any ideas?

u8k
  • 19
  • 3
  • 1
    The imgur site allows only get request as cors, so this answer should be the only solution https://stackoverflow.com/a/47822013/8155208 – Sudhanshu Kumar Jan 27 '21 at 02:18
  • Solved! Thank you both, that was it. The browser was blocking my AJAX request and I thought it just wasn't allowed to an external site. But there was just one parameter I needed to change for it to go through. Thanks! – u8k Jan 27 '21 at 02:45

0 Answers0