【问题标题】:Create folder in google drive with google-drive-ruby gem使用 google-drive-ruby gem 在 google drive 中创建文件夹
【发布时间】:2013-04-03 21:07:30
【问题描述】:

我知道这里有人问过类似的问题,但是我仍然无法完成这项工作,因为我的情况有点不同。 我希望能够使用google-drive-ruby gem 在谷歌驱动器中创建一个文件夹。

根据 Google (https://developers.google.com/drive/folder),在使用“Drive”Api 时,您可以通过插入 mime 类型为“application/vnd.google-apps.folder”的文件来创建文件夹

例如

POST https://www.googleapis.com/drive/v2/files
Authorization: Bearer {ACCESS_TOKEN}
Content-Type: application/json
...
{
  "title": "pets",
  "parents": [{"id":"0ADK06pfg"}]
  "mimeType": "application/vnd.google-apps.folder"
}

在我的情况下,我希望能够做同样的事情,但在使用 google_drive API 时。它具有接受 mime-type 选项的 upload_from_file 选项,但这仍然对我不起作用,到目前为止我得到的最好结果是执行以下代码时来自 Google 的此错误消息。

session.upload_from_file("test.zip", "test", :content_type => "application/vnd.google-apps.folder")

“Mime-type application/vnd.google-apps.folder 无效。文件不能 使用 Google mime-types 创建。

如果您能给我任何建议,我将不胜感激。

【问题讨论】:

  • 改用谷歌官方的ruby api lib是不是不合理? github.com/google/google-api-ruby-client
  • @SteveMidgley 我更新了 OP 问题的标题,以更准确地将问题/问题表示为引用 google-drive-ruby。话虽如此,我应该自己玩官方 API,因为到目前为止我一直在使用 gimite 的 gem。 =)

标签: ruby google-drive-api


【解决方案1】:

其实很简单。 Google Drive 中的文件夹是google-drive-ruby gem 中的GoogleDrive::Collection (http://gimite.net/doc/google-drive-ruby/GoogleDrive/Collection.html)。因此,您可以使用 google-drive-ruby 执行的操作是首先创建一个文件,然后通过 GoogleDrive::Collection#add(file) 方法将其添加到集合中。

这也模仿了 Google Drive 的实际工作方式:将文件上传到根集合/文件夹,然后将其添加到其他集合/文件夹。

这是我编写的一些示例代码。根据您提供的上下文,它应该可以工作 - 可能针对您的特定用例进行一些小的调整:

# this example assumes the presence of an authenticated
# `GoogleDrive::Session` referenced as `session`
# and a file named `test.zip` in the same directory
# where this example is being executed

# upload the file and get a reference to the returned
# GoogleSpreadsheet::File instance
file = session.upload_from_file("test.zip", "test")

# get a reference to the collection/folder to which
# you want to add the file, via its folder name
folder = session.collection_by_title("my-folder-name")

# add the file to the collection/folder. 
# note, that you may add a file to multiple folders
folder.add(file)

此外,如果您只想创建一个新文件夹,而不在其中放置任何文件,那么只需将其添加到根集合中:

session.root_collection.create_subcollection("my-folder-name")

【讨论】:

  • 嗨@zealoushacker 只是想问一下,我怎样才能获得搜索到的文件夹中的所有文件(使用 session.collection_by_title("folder-name") 搜索文件夹后)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多