使用Drive API写入Google文档

时间:2015-03-28 19:23:18

标签: google-drive-api

我希望在Google云端硬盘文档中创建和编写内容。

我创建了一个驱动器文档,但是无法发布我的内容。

创建文件测试文档的代码

 function createNewFile() {
      gapi.client.load('drive', 'v2', function() {

        var request = gapi.client.request({
          'path': '/drive/v2/files',
          'method': 'POST',
          'body': {
            "title": "Test.doc",
            "mimeType": "application/vnd.google-apps.document",
            "description": "Some"
          }
        });

        request.execute(function(resp) {
          console.log(resp);
          updateFile(resp.id, "Test TEXT");
        });
      });
    }

将内容添加到新创建的Google文档

的代码
function updateFile(fileId, text, callback) {

  const boundary = '-------314159265358979323846';
  const delimiter = "\r\n--" + boundary + "\r\n";
  const close_delim = "\r\n--" + boundary + "--";

  var contentType = "text/html";
  var metadata = {
    'mimeType': contentType,
  };

  var multipartRequestBody =
    delimiter + 'Content-Type: application/json\r\n\r\n' +
    JSON.stringify(metadata) +
    delimiter + 'Content-Type: ' + contentType + '\r\n' + '\r\n' +
    text +
    close_delim;

  if (!callback) {
    callback = function(file) {
      console.log("Update Complete ", file)
    };
  }

  gapi.client.request({
    'path': '/upload/drive/v2/files',
    'method': 'PUT',
    'params': {
      'fileId': fileId,
      'uploadType': 'multipart'
    },
    'headers': {
      'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
    },
    'body': multipartRequestBody,
    callback: callback,
  });
}

1 个答案:

答案 0 :(得分:0)

这是POST和UPDATE应该是什么样子。您可以使用浏览器控制台检查您的操作方式。

插入

Request URL:https://www.googleapis.com/drive/v2/files/
Request Method:POST

content-type:application/json;charset=UTF-8

{title: "delmexxx-0", mimeType: "application/vnd.google-apps.document"}

上传

Request URL:https://www.googleapis.com/upload/drive/v2/files/
18ECXade2ZfLeo?
convert=true&uploadType=media
Request Method:PUT

content-type: text/plain

some content that will become a google doc