本文介绍了覆盖Rails Paperclip插件的content_type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我有一些鸡鸡蛋问题。我想设置通过Paperclip上传的文件的content_type。问题是默认的content_type仅基于扩展名,但是我想将其基于另一个模块。

I think I have a bit of a chicken and egg problem. I would like to set the content_type of a file uploaded via Paperclip. The problem is that the default content_type is only based on extension, but I'd like to base it on another module.

我似乎能够通过以下方式设置content_type before_post_process

I seem to be able to set the content_type with the before_post_process

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才写文件。

But...I cannot base the content type on the file because Paperclip doesn't write the file until after_create.

而且我似乎无法设置content_type在保存之后或使用after_create回调(甚至返回到控制器中)

And I cannot seem to set the content_type after it has been saved or with the after_create callback (even back in the controller)

所以我想知道我是否可以通过某种方式访问实际文件对象(假设没有处理器在做保存到原始文件中的所有内容),这样我就可以在该文件上运行file_type命令。或者在创建对象之后,是否可以修改content_type。

So I would like to know if I can somehow get access to the actual file object (assume there are no processors doing anything to the original file) before it is saved, so that I can run the file_type command on that. Or is there a way to modify the content_type after the objects have been created.

推荐答案

可能您可以使用 upload.to_file 。它为您提供回形针临时文件( Paperclip :: Tempfile )。它具有 path 属性,因此您可以使用

Probably you could use upload.to_file. It gives you paperclip temporary file (Paperclip::Tempfile). It has path property, so you can use

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

您可以获得临时文件使用 upload.to_file.to_tempfile

这篇关于覆盖Rails Paperclip插件的content_type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:01