Google 驱动器 API - JavaScript 插入文件 - 创建本机 google 文档

Google Drive API - JavaScript Insert File - Create native google doc

我一直在使用 JavaScript Google 驱动器 API 来创建(插入)一个新文件。它工作得很好,除了它创建的文档不是 google 文档,而是某种可以转换为 google 文档的文档。

我想要一份实际的 google 文件。我试过 "convert:true",但它似乎无法将其转换为文档。

insertFile: function (filename, content, callback) {
  const boundary = '-------314159265358979323846';
  const delimiter = "\r\n--" + boundary + "\r\n";
  const close_delim = "\r\n--" + boundary + "--";

  {
    var contentType = 'application/vnd.google-apps.document';
    var metadata = {
      'title': filename,
      'mimeType': 'text/html',
      'description': 'Created'
    };

    // TODO: replace this with a library - https://github.com/beatgammit/base64-js/blob/master/lib/b64.js
    var base64Data = window.btoa(unescape(encodeURIComponent(content)));
    var multipartRequestBody =
        delimiter +
        'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(metadata) +
        delimiter +
        'Content-Type: ' + contentType + '\r\n' +
        'Content-Transfer-Encoding: base64\r\n' +
        '\r\n' +
        base64Data +
        close_delim;

    var request = gapi.client.request({
      'path': '/upload/drive/v2/files',
      'method': 'POST',
      'params': {'uploadType': 'multipart', 'convert': true },
      'headers': {
        'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
      },
      'body': multipartRequestBody
    });
    if (!callback) {
      callback = function (file) {
        console.log(file)
      };
    }
    request.execute(callback);
  }
}

插入文件后,当我转到 link 时,我得到:

我想我发现了你的错误。尝试迁移到 v3,根据 v3 migration:

Other changes

Imports to Google Docs formats are now requested by setting the appropriate target mimeType in the resource body, rather than specifying ?convert=true.

Import operations will return a 400 error if the format is not supported.

这是 list of supported mimeType 的 link。