gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:50 24 4
gpt4 key购买 nike

我想创建一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com