admin管理员组

文章数量:1336340

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(".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

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./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

Share Improve this question asked Jan 16, 2015 at 5:19 Extreme CodersExtreme Coders 3,5312 gold badges44 silver badges56 bronze badges 1
  • 2 Feature was requested in 2014. Bug was assigned to someone in 2017. If we're lucky, the feature will be implemented by 2020. :-) issuetracker.google./issues/36762291 – jcsahnwaldt Reinstate Monica Commented Aug 12, 2018 at 22:58
Add a ment  | 

2 Answers 2

Reset to default 7

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.

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.

本文标签: javascriptSend HEAD request in Google App ScriptStack Overflow