代码之家  ›  专栏  ›  技术社区  ›  Fotios

重写Rails回形针插件的内容类型

  •  6
  • Fotios  · 技术社区  · 16 年前

    我想我有点鸡和蛋的问题。我想设置通过回形针上传的文件的内容类型。问题是,默认的内容类型仅基于扩展,但我希望它基于另一个模块。

    我似乎能用“前-后”过程设置内容类型

    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
    

    但是…我不能基于文件的内容类型,因为剪纸在创建后才写入文件。

    我似乎无法在内容保存后或使用后创建回调(甚至在控制器中)设置内容类型。

    所以我想知道在保存文件之前是否可以访问实际的文件对象(假设没有处理器对原始文件做任何操作),这样我就可以对其运行file_type命令。或者,是否有方法在创建对象后修改内容类型?

    1 回复  |  直到 16 年前
        1
  •  4
  •   Tatjana N.    16 年前

    也许你可以用 upload.to_file . 它给你回形针临时文件( Paperclip::Tempfile )它有 path 属性,以便使用

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

    你可以得到 Tempfile 使用 upload.to_file.to_tempfile