Ahmed Kotb
Ahmed Kotb

Reputation: 6307

Update file content on google drive using javascript

Based on @Nvico great answer i was able to upload files to google drive, the problem is the code on the answer creates a new file each time, is there a way given an already created file id to update its content directly (using Files:update api) without creation of a new one ?

currently my solution is to use Files:delete api each time i want to update the file to remove the old one then create a new file using @Nvico code

Upvotes: 2

Views: 3367

Answers (1)

Alain
Alain

Reputation: 6034

Instead of using the drive.files.insert endpoint, you can use almost the same code to send an update request to the drive.files.update endpoint:

/**
 * Update existing file.
 *
 * @param {String} fileId ID of the file to update.
 * @param {Object} fileMetadata existing Drive file's metadata.
 * @param {File} fileData File object to read data from.
 * @param {Function} callback Callback function to call when the request is complete.
 */
function updateFile(fileId, fileMetadata, fileData, callback) {
  const boundary = '-------314159265358979323846';
  const delimiter = "\r\n--" + boundary + "\r\n";
  const close_delim = "\r\n--" + boundary + "--";

  var reader = new FileReader();
  reader.readAsBinaryString(fileData);
  reader.onload = function(e) {
    var contentType = fileData.type || 'application/octect-stream';
    // Updating the metadata is optional and you can instead use the value from drive.files.get.
    var base64Data = btoa(reader.result);
    var multipartRequestBody =
        delimiter +
        'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(fileMetadata) +
        delimiter +
        'Content-Type: ' + contentType + '\r\n' +
        'Content-Transfer-Encoding: base64\r\n' +
        '\r\n' +
        base64Data +
        close_delim;

    var request = gapi.client.request({
        'path': '/upload/drive/v2/files/' + fileId,
        'method': 'PUT',
        'params': {'uploadType': 'multipart', 'alt': 'json'},
        'headers': {
          'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
        },
        'body': multipartRequestBody});
    if (!callback) {
      callback = function(file) {
        console.log(file)
      };
    }
    request.execute(callback);
  }
}

The main difference is in the request URL and method:

PUT /upload/drive/v2/files/<FILE_ID>

Upvotes: 3

Related Questions