Overwriting Several Google Documents by 2 Text Files using Google Apps Script

Gists

This is a sample script for overwriting several Google Documents by 2 text files using Google Apps Script.

Before you run this sample script, please install a GAS library of FetchApp.

As a sample situation, it supposes to overwrite 2 existing Google Documents by 2 text files using the method of files.update Drive API v3. In the current stage, the batch request of Drive API cannot use the file media. This sample script might become a workaround for updating files by quasi batching request with the asynchronous process.

This script can be also used for PDF and image files.

function sample() {
  var contents = [
    {
      fileName: "newFilename1", // new filename
      docs: "### GoogleDocumentId1 ###", // Destination fileId of existing Google Document.
      textFile: "### fileId of PDF file and image files ###" // Source fileId of text file.
    },
    {
      fileName: "newFilename2",
      docs: "### GoogleDocumentId2 ###",
      textFile: "### fileId of PDF file and image files ###"
    }
  ];
  var accessToken = ScriptApp.getOAuthToken();
  var requests = contents.map(function(e) {
    var metadata = { name: e.fileName };
    var form = FetchApp.createFormData(); // Create form data
    form.append(
      "metadata",
      Utilities.newBlob(JSON.stringify(metadata), "application/json")
    );
    form.append("file", DriveApp.getFileById(e.textFile).getBlob());
    var url =
      "https://www.googleapis.com/upload/drive/v3/files/" +
      e.docs +
      "?uploadType=multipart";
    params = {
      url: url,
      method: "PATCH",
      headers: { Authorization: "Bearer " + accessToken },
      body: form
    };
    return params;
  });
  var res = FetchApp.fetchAll(requests);
  Logger.log(res);
  // DriveApp.createFile(blob) // This comment line is used for automatically detecting scope for running this sample script.
}

 Share!