Search code examples
google-apps-scriptgoogle-drive-apizipbinaryfilesurlfetch

Why Google App Script UrlFetchApp when downloads a zip file changes its binary content?


I want to download a zip file in Google Drive via Google Apps Script.

After downloading a sample zip file with the code below and saving it into the folder in google drive.

  const exampleUrl = "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-zip-file.zip";
  var response = UrlFetchApp.fetch(exampleUrl);
  var parentFolder = DriveApp.getFolderById('1aba-tnQZxZMN7DN52eAywTU-Xs-eqOf4');
  parentFolder.createFile('sample_CT.zip', response.getContentText()); // doesn't work
  parentFolder.createFile('sample_C.zip',  response.getContent());     // doesn't work
  parentFolder.createFile('sample_B.zip',  response.getBlob());        // doesn't work
  parentFolder.createFile('sample.zip',    response);                  // doesn't work

After downloading it on my machine I try to unpack with unzip utility but all of the above versions give me the following:

> unzip sample_CT.zip
Archive:  sample_CT.zip
  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of sample_CT.zip or
        sample_CT.zip.zip, and cannot find sample_CT.zip.ZIP, period.

In the picture I am comparing broken zip file (above) and the correct one (below):

broken:

PKuÔøΩÔøΩP
 sample.txtUT
ÔøΩbÔøΩ^ÔøΩbÔøΩ^ÔøΩbÔøΩ^uxÔøΩÔøΩEÔøΩ1RÔøΩ0ÔøΩÔøΩÔøΩQÔøΩ0ÔøΩUz. ,
ÔøΩÔøΩXKÔøΩ!ÔøΩÔøΩ2ÔøΩÔøΩV#ÔøΩ6ÔøΩ:
ÔøΩÔøΩMÔøΩ
��#ux�h�ttPkHTѺ�H�b+�:N�>m�����h�`{�c�0�A��(yh���&���{�U~�Y�~�����HA�����k8w�p���6�Ik��k��?k"?OJx��(n벼g�_�tPK[�c�PKu��P[�c�
 ÔøΩÔøΩsample.txtUT
ÔøΩbÔøΩ^ÔøΩbÔøΩ^ÔøΩbÔøΩ^uxÔøΩÔøΩPKX

correct:

PKu“¥P
 sample.txtUT
Çb±^Çb±^Çb±^uxèèE1RÅ0ûœâQÑ0¹Uz. ,
ÎàXKþ!·ÿ2ð‡V#í®6œ:
£èMà
ï´#ux­hð®¸ttPkHTѺòH²b+ª:Nª>mô”Éä’h˜`{úcÌ0ÅAõš(yh®©»&ÊôÏ{ýU~°YÊ~“¾ËòöHA„Äü×÷k8wÏpùö¹6ÕIk»ðk¤ü?k"?OJxºØ(në²¼gª_ötPK[°c¶PKu“¥P[°c¶
 ´sample.txtUT
Çb±^Çb±^Çb±^uxèèPKX

The image in my text editor 1

As you can see in the picture (file snippets above) some symbols differ. I have no idea why UrlFetch changes certain bytes when it downloads a zip file. Also on top it a file after UrlFetch takes more space.


Solution

  • It's because the script is converting it to string. Folder.createFile() accepts a blob, but it should be it's only argument. If it's passed as a second argument, other method signatures like Folder.createFile(name:string, content:string) takes precedence and Blob is converted to String to match the method signature.

    parentFolder.createFile(response.getBlob().setName('TheMaster.zip'))