codedread
codedread

Reputation: 1382

Updating a file contents with Google Drive v3 (JavaScript)

I'm trying to update the file contents of a file that already exists in Google Drive using JavaScript and the v3 API:

https://developers.google.com/drive/v3/reference/files/update#http-request

says that I should use the HTTP PATCH method to update a file using v3. Unfortunately it gives no examples and I can't find any reasonable documentation on what "patch semantics" mean here for file contents.

Can anyone provide an example?

Upvotes: 0

Views: 1437

Answers (3)

Rick Mohr
Rick Mohr

Reputation: 2015

Here's how to update a (JSON) file using fetch. (It's from jsGoogleDriveDemo, showing how web app users can save and open files in Google Drive using API v3 -- authorize, upload, get, update, and use the Google file picker.)

function update() {
    const url = 'https://www.googleapis.com/upload/drive/v3/files/' + fileId + '?uploadType=media';
    fetch(url, {
        method: 'PATCH',
        headers: new Headers({
            Authorization: 'Bearer ' + oauthToken,
            'Content-type': mimeType
        }),
        body: JSON.stringify({ hello: 'universe' })
    })
        .then(result => result.json())
        .then(value => {
            console.log('Updated. Result:\n' + JSON.stringify(value, null, 2));
        })
        .catch(err => console.error(err))
}

Upvotes: 0

Steve Phuc
Steve Phuc

Reputation: 1278

function createFile(accessToken) {
    // var fileContent = "sample text"; // As a sample, upload a text file.
    var fileContent = `{ test: "abc" }`; // As a sample, upload a text file.
    var file = new Blob([fileContent], { type: "text/plain" });
    var metadata = {
        name: "test", // Filename at Google Drive
        mimeType: "application/json" // mimeType at Google Drive
        // mimeType: "text/plain" // mimeType at Google Drive
        // parents: ["### folder ID ###"] // Folder ID at Google Drive
    };

    // var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
    var form = new FormData();
    form.append("metadata", new Blob([JSON.stringify(metadata)], { type: "application/json" }));
    form.append("file", file);

    fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id", {
        method: "POST",
        headers: new Headers({ Authorization: "Bearer " + accessToken }),
        body: form
    })
        .then(res => {
            return res.json();
        })
        .then(function(val) {
            console.log(val);
        });
}

you can read more here https://gist.github.com/tanaikech/bd53b366aedef70e35a35f449c51eced

Upvotes: 1

codedread
codedread

Reputation: 1382

Turns out it's simpler than I thought - there are no "patch semantics" for the file contents. The entire file contents are sent as the body of the request:

  const url = 'https://www.googleapis.com/upload/drive/v3/files/' + fileId
      + '?uploadType=media';
  xhr.open('PATCH', url);
  xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
  xhr.setRequestHeader('Content-Type', mimeType);
  xhr.onload = result => {
    console.log('Saved file to Google Drive!');
  };

Upvotes: 2

Related Questions