【问题标题】:carrierwave content_type always nil载波内容类型始终为零
【发布时间】:2012-12-14 10:46:59
【问题描述】:

我正在开发 Rails 3.2.9 应用程序并使用 Carrierwave 作为文件上传器。 Carriverwave 自述文件指出了获取正确 content_type 的方法:

  1. 将 require 'carrierwave/processing/mime_types' 添加到初始化程序或您的上传程序。
  2. 将包含 CarrierWave::MimeTypes 添加到您的上传器。
  3. 将进程 :set_content_type 添加到您的上传者。

基于此,我的上传者如下:

# encoding: utf-8
require 'carrierwave/processing/mime_types'
class AttachmentUploader < CarrierWave::Uploader::Base
  include CarrierWave::MimeTypes
  storage :file
  def store_dir
    "#{base_store_dir}/#{model.id}"
  end
  process :set_content_type

end

在我的模型中,将上传器挂载为文件:

mount_uploader :file, AttachmentUploader

但是,上传文件后我总是得到 content_type nil:

1.9.3-p327 :013 > a.file.class
 => AttachmentUploader
1.9.3-p327 :010 > a.file.file
 => #<CarrierWave::SanitizedFile:0x00000004046330 @file="uploads/course/000/000/026/attachment_file/6/myIcon.png", @original_filename=nil, @content_type=nil> 

有什么建议吗?谢谢。

PS:我已经在我的Gemfile 中添加了gem "mime-types", "~&gt; 1.19"

【问题讨论】:

    标签: ruby-on-rails carrierwave


    【解决方案1】:

    您需要按照此处列出的说明进行操作:https://github.com/carrierwaveuploader/carrierwave#setting-the-content-type

    添加 mime-types gem,然后像这样设置您的上传器文件

    require 'carrierwave/processing/mime_types'
    
    class MyUploader < CarrierWave::Uploader::Base
        include CarrierWave::MimeTypes
    
        process :set_content_type
     end
    

    【讨论】:

      【解决方案2】:

      在我安装上传器的模型文件中尝试过同样的问题

      before_save :set_mime_type                   
      
          def set_mime_type
            self.mimetype = Mime::Type.lookup_by_extension(File.extname(self.cf_filename.to_s)[1..-1]) 
          end
      

      注意:你需要在表格中有一个 mimetype 字段

      【讨论】:

        【解决方案3】:

        我刚刚遇到了完全相同的问题,但找不到简单的解决方法。

        我的解决方法是在模型中添加一个 content_type 列,并在创建/更新过程中使用

        @model.content_type = params[:file_upload][:attachment].content_type
        

        这可行,但希望问题得到解决。

        【讨论】:

          猜你喜欢
          • 2016-07-16
          • 1970-01-01
          • 1970-01-01
          • 2018-10-05
          • 1970-01-01
          • 2016-05-02
          • 2012-01-16
          • 2020-01-07
          • 1970-01-01
          相关资源
          最近更新 更多