首页 > 解决方案 > 使用 google-api-ruby-client 将文本写入 google doc 文件

问题描述

我正在尝试使用google-api-ruby-client将一些文本写入新的 google doc 文件。

我认为以下应该有效,但它没有:

file_metadata = {
  name: "Testing",
  mime_type: 'application/vnd.google-apps.document'
}

@drive.create_file(file_metadata,
                   fields: 'id',
                   upload_source: StringIO.new("tt"),
                   content_type: 'text/text')

当我运行这个时,我得到Google::Apis::ClientError: badRequest: Bad Request


更新:在 Tanaike 在下面发布正确答案后,我还必须移动文件,因为它是在我的服务用户的根目录中创建的。最终(工作)代码如下所示

file_metadata = {
  name: "Filename",
  mime_type: 'application/vnd.google-apps.document'
}

file = @drive.create_file(file_metadata,
                   fields: 'id,parents',
                   upload_source: StringIO.new("Text to go in file"),
                   content_type: 'text/plain')

current_parent = file.parents.first
@drive.update_file(file.id, nil,
                   add_parents: "#{@folder_id}",
                   remove_parents: "#{current_parent}")

标签: rubygoogle-docsgoogle-docs-api

解决方案


这个改装怎么样?在这种情况下,文本的 mimeType 是text/plain.

从:

content_type: 'text/text'

到:

content_type: 'text/plain'

笔记:

  • 在我的环境中,当我使用 时content_type: 'text/text',会发生同样的错误。当我使用 时content_type: 'text/plain',包含文本的 Google 文档tt会创建到 Google Drive 的根文件夹中。
  • 在这种情况下,它假设您@drive可以用于上传文件。

参考:


推荐阅读