Search code examples
corsxmlhttprequestfetch

JavaScript get file size hosted on another origin without control of crossorigin headers


Here is a dummy PDF file available for download: https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf

This is hosted on w3.org so I definitely won't have control of response headers.

My requirement is to render an <a download href="...">Download PDF</a> element to download the file, but before downloading I also want to get the file size and display it. Under the same origin, this can be done by (await fetch('...', { method: 'HEAD' })).headers.get('content-length'), but my approach was blocked by CORS: enter image description here

This is expected, as they are not in the same region. Wondering whether there's any way to workaround this based on the fact I don't own or am able to edit the response header of the origin that is hosting the file I need to download?


Solution

  • Without control of the destination site, you will need to, like @Bergi suggests in the comments, create a proxy to get the size of the pdf. The implementation of this will differ depending on what language and framework you use, but the general idea would be to, when your api endpoint is accessed, make an http request from your backend to the target pdf, get the size, and send it in the http response. Because your backend code is not bound by the CORS rules enforced by browsers, it will be able to successfully retrieve the information you need.

    You can learn more about CORS and how it works on Mozilla's developer documentation site