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


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

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

我能够更新文件元数据(例如名称),但文档不包含实际文件内容的补丁语义。有没有办法通过 JSON.stringify() 作为一个参数的价值 gapi.client.drive.files.update 请求:

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)

9990
2017-11-15 01:42


起源



答案:


有两个问题:

  1. JavaScript客户端库不支持媒体上载。
  2. 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文档可以导入的文件类型,例如.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);
  });
}

9
2018-01-04 15:16





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

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

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

6
2018-01-06 18:13