2

我正在使用具有以下型号的 Paperclip 4.2 + Rails 4.1.6:

class Post < ActiveRecord::Base

  has_attached_file :featured_image, styles: { :medium => "300x300>", :thumb => "100x100>" }
  validates_attachment :featured_image, :content_type => { :content_type => ["image/jpeg", "image/gif", "image/png"] }


  def featured_image_from_url(url)
    self.featured_image = URI.parse(url)
  end

end

当我在表单中使用文件上传器上传文件时,一切正常。设置附件并生成缩略图。

但是,如果我尝试使用指向 jpeg 图像的远程 URL,如在此处指定,则无法保存帖子,因为附件的内容类型错误:featured_image_content_type: "binary/octet-stream"

如果我通过手动设置来强制内容类型:

post.featured_image_content_type = "image/jpeg"
post.save

则模型保存成功。

4

2 回答 2

2

嗨,我不知道您是否找到了解决方法。当网络服务器返回不正确的内容类型时,我使用了以下代码(针对您的示例进行了修改)来阻止 Paperclip(4.2.1)引发异常:

def featured_image_from_url(url)
  self.featured_image = URI.parse(url)
  # deal with the case where the webserver
  # returns an incorrect content-type
  adapter = Paperclip.io_adapters.for(featured_image)
  self.featured_image_content_type = Paperclip::ContentTypeDetector.new(adapter.path).detect
end

可能有更整洁或更正确的方法!

于 2015-04-20T23:11:21.543 回答
1

这是一个可以帮助您下​​载 url 的 gem,Tempfile这样您就可以解决 s3 发送流 mime 类型的问题https://github.com/equivalent/pull_tempfile

于 2016-03-21T14:22:28.817 回答