Rails:如何从 http 下载文件并将其保存到数据库中 [英] Rails: How to to download a file from a http and save it into database

查看:35
本文介绍了Rails:如何从 http 下载文件并将其保存到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i would like to create a Rails controller that download a serie of jpg files from the web and directly write them into database as binary (I am not trying to do an upload form)

有什么线索可以做到这一点吗?

Any clue on the way to do that ?

谢谢

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

Edit : Here is some code I already wrote using 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
}

我得到一个未定义的方法`content_type' for #"错误

And I get an "undefined method `content_type' for #" error

推荐答案

使用 open-url(在 Ruby 标准库中)获取文件,然后使用像 回形针 将它们作为模型的附件存储在数据库中.

Use open-url (in the Ruby stdlib) to grab the files, then use a gem like paperclip to store them in the db as attachments to your models.

更新:

Attachment_fu 不接受原始字节,它需要一个类文件"对象.使用 这个 LocalFile 示例 以及下面的代码将图像转储到临时文件中,然后发送到您的模型.

Attachment_fu does not accept the raw bytes, it needs a "file-like" object. Use this example of a LocalFile along with the code below to dump the image into a temp file then send that to your model.

  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
  }

这篇关于Rails:如何从 http 下载文件并将其保存到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆