0

The following snippet of code computes the size of files located at url on my local system using Javascript

//returns file size given a URL
function getFileSize(url, key)
{
    var fileSize = '';
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);

    http.onreadystatechange = function() {
        if (this.readyState == this.DONE) {
            if (this.status == 200) {
                fileSize = this.getResponseHeader('content-length');

                //saves size in dictionary sizes
                sizes[key] = fileSize;
             }
        }
  };
  http.send();
}

When I deploy the code to my Apache server, however, this.getResponseHeader returns null, although the provided url correctly points to a file. I am considering different options for why this is the case (e.g., incorrect file permissions) but haven't found a solution yet. I also followed this link to change my server configuration to allow CORS but that didn't help. Any help would be greatly appreciated.

lupod
  • 144
  • 1
  • 11
  • check the network tab, whats the status code of the request? – Khalil Jul 17 '22 at 07:24
  • @Khalil - at a guess, 200 ... since it has to be 200 for `this.getResponseHeader('content-length')` to even execute, let alone return "null" – Jaromanda X Jul 17 '22 at 07:48
  • 1
    You don't need to guess, the network tab in the dev tools will show you the status of the request. – Khalil Jul 17 '22 at 07:54
  • Yes, the status of the request is 200 both locally and on the server – lupod Jul 17 '22 at 14:19
  • 1
    While you are looking at the network tab, is the Apache server including the **optional** `content-length` header in the response? – Quentin Jul 17 '22 at 20:10
  • It was not included and I couldn't figure out why. I finally found out that some settings in my .htaccess were preventing the server to send content-length (see answer below). – lupod Jul 17 '22 at 21:10

1 Answers1

0

I fixed the issue. In my .htaccess, I had added some filters to allow for HTML compression as explained here. However, this made my Apache server not include content-length in the html response (see here for more details). By getting rid of HTML compression in .htaccess, content-length is now included by the server.

lupod
  • 144
  • 1
  • 11