'Google Drive REST API - Corrupted ZIP file after upload

I'm using the Google Drive REST API to upload a ZIP file but all my ZIP files become corrupted after the upload. When I download the file and then try to unzip it on my computer, on MacOS it says "Unable to expand 'FILE_NAME.zip' into FOLDER. Error 79 - Inappropriate file type or format.". I made sure it wasn't just my computer by having another person on a different computer try to unzip it and they had the same problem. I also confirmed that the ZIP file wasn't becoming corrupted before I uploaded it to Google Drive.

Below is a simplified version of my code.

const async = require('async');
const requestModule = require('request');
const fs = require('fs');
var api = {};
var tasks = {
  // first, get the zip file contents
  'getFile': function(cb) {
    fs.readFile('my_file.zip', {'encoding':'UTF-8'}, function(err, data) {
      if (err) {
        console.error(err);
        return cb();
      }
      api.file_data = data;
      cb();
    });
  },
  // second, upload the file contents to google drive via their API
  'uploadFile': function(cb) {
      var metadata = {
        'mimeType': 'application/zip',
        'name': 'my_file.zip'
      };
      var request = {
        'url': 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true',
        'method': 'POST',
        'headers': {
          'Authorization': 'Bearer ' + GOOGLE_ACCESS_TOKEN,
          'Content-Type': 'multipart/related; boundary="SECTION"'
        },
        'body': '--SECTION\r\n' +
                'Content-Type: application/json; charset=UTF-8\r\n' +
                '\r\n' +
                JSON.stringify(metadata) + '\r\n' +
                '\r\n' +
                '--SECTION\r\n' +
                'Content-Type: application/zip\r\n' +
                'Content-Transfer-Encoding: base64\r\n' +
                '\r\n' +
                new Buffer.from(api.file_data).toString('base64') + '\r\n' +
                '\r\n' +
                '--SECTION--'
      };
      requestModule(request, function(err, res, body) {
        if (err) {
          console.error(err);
          return cb();
        }
        cb();
      });
   }
};
async.series(tasks, function() {
  console.log('Done');
});

Note: I'm doing a Q&A-style post and will be answering my own question.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source