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

时间:2016-11-15 01:42:51

标签: javascript google-drive-api

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

https://developers.google.com/drive/v3/reference/files/update

我能够更新文件元数据(例如名称),但文档中没有包含实际文件内容的补丁语义。有没有办法在def display(self): print("Positon: {},Direction: Up".format(self.position)) >>> a.display() Positon: 3,Direction: Up 请求中将 import pandas def createDictionary(filename): my_data = pandas.DataFrame.from_csv(filename, sep=',', index_col=False) list_of_dicts = [item for item in my_data.T.to_dict().values()] return list_of_dicts if __name__ == "__main__": x = createDictionary("textToEnglish.csv") print type(x) # <class 'list'> print len(x) # 4255 print type(x[0]) # <class 'dict'> 值作为参数传递:

JSON.stringify()

3 个答案:

答案 0 :(得分:12)

有两个问题:

  1. JavaScript客户端库不支持媒体上传。
  2. Google文档文件没有本机文件格式。
  3. 您可以通过编写基于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文档可以导入的文件类型,例如.txt,.docx等。以下代码使用上述功能使用纯文本更新Google文档的内容:

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

答案 1 :(得分:7)

我使用javascript v3 api构建gDriveSync.js库以与google驱动器同步https://github.com/vitogit/gDriveSync.js

您可以查看我所做的事情的源代码(https://github.com/vitogit/gDriveSync.js/blob/master/lib/drive.service.js),基本上是一个两步过程,首先创建文件然后更新它。

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

答案 2 :(得分:0)

假设您已经将令牌存储在名为tokens的var中,则可以使用node-js google API通过抓取来完成此操作:

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