google-apps-scriptgoogle-drive-api

How to receive --data-binary from post request in google drive app script


Here is my request

    curl --location --request POST 'https://script.google.com/macros/s/{My Web app url}/exec' \
--header 'Content-Type:  application/octet-stream' \
--header 'fileName: MyFileName' \
--header 'mimeType: application/octet-stream' \
--data-binary '@/Location/To/My/Local/File'

I am trying to receive this request in my google drive app script

function doPost(e) {
  var data = Utilities.base64Decode(e.postData.contents); <---- having issue with this line
  var blob = Utilities.newBlob(data, e.postData.type, "TempFile");
  var fileId = DriveApp.createFile(blob);
  
  return ContentService.createTextOutput("fileName:"+fileName + " fileId:" + fileId);
}

The file is binary, not image not zip, but other type of binary

What do I need to write to make it work ?


Solution

  • Modification points:

    When above points are reflected to your curl command and script, those become as follows.

    Modified curl command:

    In order to send the file data as the base64 data, how about the following modified curl command?

    curl --location 'https://script.google.com/macros/s/{My Web app url}/exec' \
    --header 'Content-Type: application/octet-stream' \
    --data '{"file":"'"$(base64 /Location/To/My/Local/File)"'","filename":"sampleFilename"}'
    

    Modified Google Apps Script:

    In order to use the data from above curl command, how about the following modification?

    function doPost(e) {
      var contents = JSON.parse(e.postData.contents.replace(/\n/g, ""));
      var fileName = contents.filename;
      var data = Utilities.base64Decode(contents.file);
      var blob = Utilities.newBlob(data, e.postData.type, fileName);
      var fileId = DriveApp.createFile(blob).getId();
      return ContentService.createTextOutput("fileName:" + fileName + " fileId:" + fileId);
    }
    

    Note:

    References: