使用Google Drive v3(JavaScript)更新文件内容

时间:2016-05-05 11:33:19

标签: javascript google-api google-drive-api updates

我尝试使用JavaScript和v3 API更新Google云端硬盘中已存在的文件的文件内容:

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

说我应该使用HTTP PATCH方法使用v3更新文件。不幸的是,它没有给出任何例子,我找不到任何关于"补丁语义的合理文档"这里指的是文件内容。

有人能提供一个例子吗?

2 个答案:

答案 0 :(得分:1)

事实证明它比我想象的更简单 - 没有"补丁语义"对于文件内容。整个文件内容作为请求的正文发送:

  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!');
  };

答案 1 :(得分:0)

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);
        });
}

您可以在这里https://gist.github.com/tanaikech/bd53b366aedef70e35a35f449c51eced

了解更多信息