覆盖Rails Paperclip插件的content_type

6

我认为我有一个棘手的问题。我想设置通过Paperclip上传的文件的content_type。问题在于默认的content_type仅基于扩展名,但我想基于另一个模块。

我似乎可以使用before_post_process设置content_type。

class Upload < ActiveRecord::Base 
  has_attached_file :upload
  before_post_process :foo

  def foo
    logger.debug "Changing content_type"

    #This works
    self.upload.instance_write(:content_type,"foobar")

    # This fails because the file does not actually exist yet
    self.upload.instance_write(:content_type,file_type(self.upload.path)
  end

  # Returns the filetype based on file command (assume it works)
  def file_type(path)
    return `file -ib '#{path}'`.split(/;/)[0]
  end
end

但是...我不能基于文件来确定内容类型,因为Paperclip在after_create之后才写入文件。

而且我似乎无法在保存后或使用after_create回调(即使在控制器中)设置content_type。

所以我想知道是否可以在保存之前以某种方式访问实际的文件对象(假设没有处理器对原始文件进行任何操作),以便我可以在其上运行file_type命令。或者是否有一种方法可以修改对象创建后的content_type。

1个回答

4

你可以使用upload.to_file。它会给你一个临时文件(Paperclip::Tempfile)。它有一个path属性,所以你可以使用:

self.upload.instance_write(:content_type,file_type(self.upload.to_file.path)

您可以使用 upload.to_file.to_tempfile 来获取 Tempfile

1
获取临时文件正是我所需要的。我还将其从 before_post_process 更改为 before_save - Fotios

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