Paperclip可以保存没有扩展名的远程图片

3

这里有一个控制器

require 'open-uri'

user = User.new
url = "some_remote_image.jpg" #remote image WITH extension
user.image = open(url)
user.save

模型

has_attached_file :image,
  :styles => { :thumb => "25x25>", :large => "1000x1000>" }, 
  :path => ":rails_root/images/users/:id/:style/:hash.:extension",
  :url => "/images/users/:id/:style/:hash.:extension",
:hash_secret => "hash string"

这个方法可以工作,但图像没有扩展名,比如“some_remote_image.” 如果通过表单上传图像,则所有内容都将包含扩展名。 我有点困惑。
2个回答

4
我通过将Paperclip更新到最新的Github版本并使用以下方式设置图像来解决了这个问题,而不是使用user.image = open(url)。
user.image = URI.parse(url)

我认为你的意思是: user.image = URI.parse(url) - oshikryu
我也遇到了同样的问题,上面的解决方案有效,但副作用是只创建了一个样式(没有缩略图)。该如何解决? - Imran Ahmad

3
如果有人想要反向操作,可以为无扩展名的文件添加扩展名。
  def besfore_save
    tempfile = data.queued_for_write[:original]
    unless tempfile.nil?
      extension = File.extname(tempfile.original_filename)
      if !extension || extension == ''
        mime = tempfile.content_type
        ext = Rack::Mime::MIME_TYPES.invert[mime]
        self.data.instance_write :file_name, "#{tempfile.original_filename}#{ext}"
      end
    end

    true
  end

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