Rails:如何从HTTP下载文件并将其保存到数据库中

7
我希望创建一个Rails控制器,可以从网络上下载一系列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 #"错误。
1个回答

6
使用 Ruby 标准库中的 open-url 获取文件,然后使用像 paperclip 这样的 gem 将它们作为附件存储到您的模型中。
更新:
Attachment_fu 不接受原始字节,它需要一个“类似文件”的对象。结合下面的代码和 这个本地文件的示例 将图像转储到临时文件中,然后将其发送到您的模型。
  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
  }

谢谢,我已经尝试过另一个宝石来实现这个功能,但没有成功。请参见我上面的示例代码。 - Chris
content_type未定义,因为attachement_fu期望的是一个文件,而不是字节流。我已经更新了我的答案,并附上了一些代码。 - Jonathan Julian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接