【问题标题】:Retrieve MongoDB GridFS file using Ruby使用 Ruby 检索 MongoDB GridFS 文件
【发布时间】:2016-01-01 11:06:37
【问题描述】:

我正在尝试检索使用 GridFS 成功存储的二进制文件。 我在 Mac OS X 上使用 MongoDB v3.0.6、Ruby 2.0.0 和 MongoDB Ruby Driver v 2.0.1。

有没有可行的例子?

【问题讨论】:

    标签: ruby mongodb gridfs


    【解决方案1】:

    查看文档,这似乎应该可行:

    client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
    client.database.fs.find_one(:filename => 'new-file.txt') #=> Returns a Mongo::Grid::File
    

    以下是将其流式传输到文件的方法:

    client.database.fs.open_download_stream(file_id) do |stream|
      IO.write('some-file', stream.read)
    end
    

    【讨论】:

    • 这将返回一个 Mongo::Grid::File 变量。我想获取实际存储的文件。到目前为止,我没有运气。
    • “得到”它是什么意思...?
    • 保存实际文件。
    • 已保存。如果需要,您可以将其流式传输到另一个文件?
    • 怎么样?我正在寻找这样做的 Ruby 代码(使用 MongoDB Ruby Driver v2.0.1)。
    【解决方案2】:

    以下代码有效:

    require 'rubygems'
    require 'mongo'
    include Mongo
    
    $client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'garden')
    Mongo::Logger.logger.level = ::Logger::ERROR
    $files = $client[:files]
    
    puts 'connected!'
    
    # Upload file
    fs = $client.database.fs 
    $file = File.open("delete.rb")
    $file_id = fs.upload_from_stream("delete.rb", $file)
    $file.close
    
    $file_to_write = File.open('perfectCopy', 'w')
    fs.download_to_stream($file_id, $file_to_write)
    

    米哈利斯。

    【讨论】:

      猜你喜欢
      • 2012-03-29
      • 2014-03-29
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 2014-12-05
      • 2013-01-02
      • 2015-07-21
      相关资源
      最近更新 更多