7

I am developing a Google App Script to determine the size of a remote resource without downloading it. The code is as follows

function getRemoteFileSize()
{  
  var params =  { "method" : "head" };
  var resp = UrlFetchApp.fetch("https://www.google.com/images/srpr/logo11w.png", params);
  Logger.log("Remote File Size: " + resp.getAllHeaders()["Content-Length"]);
}

However, Google App Script does not seem to support head requests and the code above cannot be executed.

What can be a viable alternative other than issuing a GET request ?
I am open to all suggestions including usage of a third-party service which has an API

Extreme Coders
  • 3,441
  • 2
  • 39
  • 55

2 Answers2

6

You can try to override the method by setting the "headers" advanced parameter:

var params = {"method" : "GET", "headers": {"X-HTTP-Method-Override": "HEAD"}};

I've never used "HEAD", so I can't tell you for sure that this will work, but I have used the method override for "PATCH", and had that work.

Alan Wells
  • 30,746
  • 15
  • 104
  • 152
  • It's definitely working but how can we be sure that it's issuing a `HEAD` request and not a `GET` request. – Extreme Coders Jan 16 '15 at 18:42
  • You can probably use your browsers developer tools to view the network requests. Chrome has built in developer tools. You can add FireBug to browsers. – Alan Wells Jan 16 '15 at 18:51
  • 1
    I just tried this and it doesn't work. I tested by send a urlFetchApp request to an Apache web server that I have access to and tailing the access.log. The request was still GET. – Jimadine Jul 28 '15 at 18:08
  • 1
    Downvote: Won't work for most URLs. As far as I know, most HTTP servers must be specially configured to make this work. In other words, if you can configure the server that serves the URL, you may be able to make this work. Otherwise, it's very unlikely that this will help. See https://www.hanselman.com/blog/HTTPPUTOrDELETENotAllowedUseXHTTPMethodOverrideForYourRESTServiceWithASPNETWebAPI.aspx (The answer mentions PATCH, but to send a PATCH request, one can just use `{method : "PATCH"}`.) – jcsahnwaldt Reinstate Monica Aug 12 '18 at 16:29
3

I found that for my circumstance, I was able to use the Range header to request 0 bytes and then inspect the response headers which held the file size:

var params = {
    method: "GET",
    headers: {
      Range: "bytes=0-0",
    },
  };
  var response = UrlFetchApp.fetch(fileUrl,params);
  var headers = response.getHeaders();
  var fileSizeString = headers['Content-Range']
  var fileSize = +headers['Content-Range'].split("/")[1];

The response headers had Content-Range=bytes 0-0/139046553 as a value that I could then use to convert to an integer (139046553) number of bytes.

  • At least it works for files stored by Google (I tried with images from Google Drive elements and images stored in Google Cloud Storage) ! – ValLeNain Feb 19 '23 at 11:39