加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 纸张剪贴画:从网址上传到扩展名

发布时间:2020-12-16 20:16:28 所属栏目:百科 来源:网络整理
导读:我想通过S3存储上的回形针从URL上传图片. 我一起工作: Ruby 1.9.3Rails 3.2.6paperclip 3.1.3aws-sdk 1.3.9 我有我的图片型号: class Asset has_attached_file :asset,:styles = {:thumb = "60x60"},:storage = :s3,:s3_credentials = "#{Rails.root}/conf
我想通过S3存储上的回形针从URL上传图片.
我一起工作:
Ruby 1.9.3
Rails 3.2.6
paperclip 3.1.3
aws-sdk 1.3.9

我有我的图片型号:

class Asset

  has_attached_file :asset,:styles => {:thumb => "60x60>"},:storage => :s3,:s3_credentials => "#{Rails.root}/config/s3.yml",:path => "/pictures/:id/:style.:extension"

  validates_attachment_content_type :asset,:content_type => ['image/gif','image/jpeg','image/png','image/x-ms-bmp']

end

所以基本上我做这个从一个URL下载我的文件:

picture = Asset.new(asset: open("http://www.my_url.com/my_picture.jpg"))
picture.save

但它保存我的文件与一个坏的file_name,它不设置文件的扩展名:

#<Asset id: 5,asset_file_name: "open-uri20120717-6028-1k3f7xz",asset_content_type: "image/jpeg",asset_update_at: nil,asset_file_size: 91565,created_at: "2012-07-17 12:41:40",updated_at: "2012-07-17 12:41:40">
p.asset.url
  => http://s3.amazonaws.com/my_assets_path/pictures/5/original.

正如你可以看到没有扩展.

我找到了一种方法来解决它,但我确定我可以有一个更好的方法.这个解决方案是将文件复制到我的电脑上,然后在S3上发送它,就像这样:

filename = "#{Rails.root}/tmp/my_picture.jpg"
open(filename,'wb') do |file|
  file << open("http://www.my_url.com/my_picture.jpg").read
end

picture = Asset::Picture.new(asset: open(filename))
picture.save

这在我的电脑上有效:

#<Asset::Picture id: 10,asset_file_name: "my_picture.jpg",created_at: "2012-07-17 12:45:30",updated_at: "2012-07-17 12:45:30">
p.asset.url
  => "http://s3.amazonaws.com/assets.tests/my_assets_path/10/original.jpg"

但是我不知道这个方法是否可以在Heroku上工作(我托管我的应用程序).

没有一个更好的方式没有通过一个临时文件?

解决方法

好时机.我刚刚在几个小时前(2012年7月20日)发送了一个拉链请求,这应该使你的生活真正容易.
self.asset = URI.parse("http://s3.amazonaws.com/blah/blah/blah.jpg")

这将下载您的jpeg图像,确保文件名为blah.jpg,内容类型为“image / jpg”

纸夹版本> 3.1.3(您需要将其链接到github repo直到它被释放).

更新:确认使用回形码版本> = 3.1.4

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读