Extreme Coders
Extreme Coders

Reputation: 3511

Send HEAD request in Google App Script

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

Upvotes: 7

Views: 1694

Answers (2)

Collin Smith
Collin Smith

Reputation: 41

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.

Upvotes: 3

Alan Wells
Alan Wells

Reputation: 31300

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.

Upvotes: 7

Related Questions