Google Drive API V3(javascript)更新文件内容

Google Drive API V3(javascript)更新文件内容,javascript,google-drive-api,Javascript,Google Drive Api,我想使用Google Drive API V3(javascript)更新Google文档的内容: 我可以更新文件元数据(例如名称),但是文档中没有包含实际文件内容的补丁语义。是否有方法在gapi.client.drive.files.update请求中将JSON.stringify()值作为参数传递: var request = gapi.client.drive.files.update({ 'fileId': fileId, 'name' : 'Updated File

我想使用Google Drive API V3(javascript)更新Google文档的内容:

我可以更新文件元数据(例如名称),但是文档中没有包含实际文件内容的补丁语义。是否有方法在
gapi.client.drive.files.update
请求中将
JSON.stringify()
值作为参数传递:

var request = gapi.client.drive.files.update({
    'fileId': fileId,
    'name' : 'Updated File Name',
    'uploadType': 'media',
    'mimeType' : 'application/vnd.google-apps.document'
  });

var fulfilledCallback = function(fulfilled) { 
    console.log("Update fulfilled!", fulfilled);
};
var rejectedCallback = function(rejected) { 
    console.log("Update rejected!", rejected);
};

request.then(fulfilledCallback, rejectedCallback)
有两个问题:

  • JavaScript客户端库不支持媒体上载
  • Google文档文件没有本机文件格式
  • 您可以通过在XHR之上编写自己的上传功能来解决问题1。以下代码应适用于大多数现代web浏览器:

    function updateFileContent(fileId, contentBlob, callback) {
      var xhr = new XMLHttpRequest();
      xhr.responseType = 'json';
      xhr.onreadystatechange = function() {
        if (xhr.readyState != XMLHttpRequest.DONE) {
          return;
        }
        callback(xhr.response);
      };
      xhr.open('PATCH', 'https://www.googleapis.com/upload/drive/v3/files/' + fileId + '?uploadType=media');
      xhr.setRequestHeader('Authorization', 'Bearer ' + gapi.auth.getToken().access_token);
      xhr.send(contentBlob);
    }
    
    要解决问题#2,您可以向驱动器发送Google Docs可以从中导入的文件类型,如.txt、.docx等。以下代码使用上述函数使用纯文本更新Google Doc的内容:

    function run() {
      var docId = '...';
      var content = 'Hello World';
      var contentBlob = new  Blob([content], {
        'type': 'text/plain'
      });
      updateFileContent(fileId, contentBlob, function(response) {
        console.log(response);
      });
    }
    

    我构建了gDriveSync.js库,使用javascript v3 api与google drive同步

    您可以检查我所做的()的源代码,基本上是一个两步过程,首先创建文件,然后更新它

      this.saveFile = function(file, done) {
        function addContent(fileId) {
          return gapi.client.request({
              path: '/upload/drive/v3/files/' + fileId,
              method: 'PATCH',
              params: {
                uploadType: 'media'
              },
              body: file.content
            })
        }
        var metadata = {
          mimeType: 'application/vnd.google-apps.document',
          name: file.name,
          fields: 'id'
        }
        if (file.parents) {
          metadata.parents = file.parents;
        }
    
        if (file.id) { //just update
          addContent(file.id).then(function(resp) {
            console.log('File just updated', resp.result);
            done(resp.result);
          })
        } else { //create and update
          gapi.client.drive.files.create({
            resource: metadata
          }).then(function(resp) {
            addContent(resp.result.id).then(function(resp) {
              console.log('created and added content', resp.result);
              done(resp.result);
            })
          });
        }
      }
    

    假设您已经将令牌存储在名为
    tokens
    的变量中,您可以使用node js google API通过fetch来实现这一点:

    fetch("https://www.googleapis.com/upload/drive/v3/files/ID_OF_DRIVE_FILE?uploadType=media",
            {   
                headers: {
                    'Content-Type':'multipart/related; boundary=a5cb0afb-f447-48a6-b26f-328b7ebd314c',
                    'Accept-Encoding': 'gzip',
                    'User-Agent': 'google-api-nodejs-client/0.7.2 (gzip)',
                    Authorization:tokens.token_type +" "+ tokens.access_token,
                    Accept:"application/json"
                },
                method:"PATCH",
                body: "OK now iasdfsdgeaegwats AGAIN intresting",
                cb(r) {
    
                }
            }).then(r => {
                console.log(r);
            });