ruby-on-rails - rails : How to to download a file from a http and save it into database

标签 ruby-on-rails ruby

我想创建一个 Rails Controller ,从网上下载一系列 jpg 文件,并直接将它们作为二进制文件写入数据库 (我不是要上传表格)

关于如何做到这一点的任何线索?

谢谢

编辑: 这是我已经使用 attachment-fu gem 编写的一些代码:

http = Net::HTTP.new('awebsite', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start() { |http|
   req = Net::HTTP::Get.new("image.jpg")
   req.basic_auth login, password
   response = http.request(req)
   attachment = Attachment.new(:uploaded_data => response.body)
   attachement.save
}

我得到一个“undefined method `content_type' for #”错误

最佳答案

使用open-url (在 Ruby stdlib 中)获取文件,然后使用像 paperclip 这样的 gem将它们作为模型的附件存储在数据库中。

更新:

Attachment_fu 不接受原始字节,它需要一个“类文件”对象。使用 this example of a LocalFile连同下面的代码将图像转储到临时文件中,然后将其发送到您的模型。

  http = Net::HTTP.new('www.google.com')
  http.start() { |http|
     req = Net::HTTP::Get.new("/intl/en_ALL/images/srpr/logo1w.png")
     response = http.request(req)
     tempfile = Tempfile.new('logo1w.png')
     File.open(tempfile.path,'w') do |f|
       f.write response.body
     end
     attachment = Attachment.new(:uploaded_data => LocalFile.new(tempfile.path))
     attachement.save
  }

关于ruby-on-rails - rails : How to to download a file from a http and save it into database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2571547/

相关文章:

Ruby activerecord 两个表与 ActiveRecord 的外连接

ruby-on-rails - 在图像上传程序的支持下,我可以在Rails 3.1应用程序中使用哪些所见即所得编辑器?

ruby - 如何干燥在多个上下文中重复的测试用例?

ruby-on-rails - 为什么 Rails Gemfile 默认为 https 而 http 使 bundler 更快?

ruby-on-rails - Rails Amazon S3 如何创建文件上传进度条?

ruby - 如何在 Ruby 中抓取、解析和抓取文件?

javascript - Rails Ajax 部分传递表单生成器

ruby-on-rails - "No resource or method named ` windows_package ' "使用 chef 安装简单的 windows 包时

ruby-on-rails - Ruby on Rails : How to set a Cookie?

ruby-on-rails - 如何使用 Rails 3 和多个 check_box_tag 元素同时删除多条记录