Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

any way to get file size from url without downloading it using google app script.?

Actually I don't know how can I make a head request and read content-length. I tried to write this function:

function getfilesize(url) {
  var msg = '';
  var response;

  try {
    response = UrlFetchApp.fetch(url, {
      // muteHttpExceptions: true,
      // validateHttpsCertificates: false,
      followRedirects: true  // Default is true anyway.
    });
catch(e) {
    return e.toString();
  }

var headers = response.getHeaders();
      var content_length = NaN;
      for (var key in headers) {
        if (key.toLowerCase() == 'Content-Length'.toLowerCase()) {
          content_length = parseInt(headers[key], 10);
          break;
        }

      }
return content length;
}

but it returns a value of 1.81619173E8 for 173mb in 60 sec. Can anyone suggest another way of doing it faster with google apps script?

like image 732
Shubham Soni Avatar asked Oct 28 '25 00:10

Shubham Soni


2 Answers

Your code is probably about correct. That 1.81619173E8 is 1816191730 bytes, which is 173MB. Content-Length is always in bytes.

To convert it to MB, just divide by 1024 twice (once puts it in KB, once more for MB).

content_length = parseInt(headers[key], 10) / 1024 / 1024;

For changing the request type, it looks like fetch() won't accept HEAD directly, but you can use the X-HTTP-Method header to override it:

response = UrlFetchApp.fetch(url, {
  method: 'GET',
  headers: {'X-HTTP-Method-Override': 'HEAD'},
  followRedirects: true  // Default is true anyway.
});

That should get it to use HEAD instead of GET.

like image 167
samanime Avatar answered Oct 30 '25 14:10

samanime


I think its taking a long time because you are actually downloading the content.

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.

like image 35
Collin Smith Avatar answered Oct 30 '25 15:10

Collin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!