【问题标题】:Mime Type file checking only fails when uploading using Ruby on Rails只有在使用 Ruby on Rails 上传时,Mime 类型文件检查才会失败
【发布时间】:2019-09-07 02:17:54
【问题描述】:

我使用此代码将文件上传到服务器,它工作正常。

现在我正在尝试在允许使用carrierwaves 功能上传文件之前检查mime 文件类型。

我尝试按照此处link 的解决方案中的建议使用 Ruby Filemagic(),但它似乎已经过时,因为它需要低于 2.5.0 的 Ruby 版本

我的成功

我尝试使用 Ruby MIME::Types.type_for() 验证。

按照以下代码直接从磁盘读取文件时效果很好

check=MIME::Types.type_for("C:/Users/Public/Pictures/Sample Pictures/america.jpg").first.content_type

我的问题

如果我尝试在表单上传过程中读取文件,则会显示错误

undefined method `chomp' for #<ActionDispatch::Http::UploadedFile:0x0953a828>

按照下面的代码

check=MIME::Types.type_for(image_params['attachment']).first.content_type

从磁盘读取文件时的检查模式似乎与作为表单上传的一部分读取文件不同。我猜是 mime vs content_type 之类的。

这里是 image_controller

class ImagesController < ApplicationController

   def create


      print(' para: ', image_params['name'])
      print(' para: ', image_params['attachment'])

      #check=MIME::Types.type_for("C:/Users/Public/Pictures/Sample Pictures/america.jpg").first.content_type
      check=MIME::Types.type_for(image_params['attachment']).first.content_type
      print(check)

      @imagefile = Imagefile.new(image_params)

      if @image.save
         redirect_to images_path, notice: "file has been uploaded."
      else
         render "new"
      end

   end

   private
      def image_params
      params.require(:image).permit(:name, :attachment)
   end

end

附件_控制器

class AttachmentUploader < CarrierWave::Uploader::Base

   storage :file

    def store_dir
       "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
   end

   def extension_white_list
      %w(pdf doc htm html docx png jpg gif)
   end

图像模型

class Image < ApplicationRecord
   mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model.

   validates :name, :attachment, presence: true # Make sure the owner's name is present.

end

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    mimemagic gem 适合我

    通过扩展名和内容检测文件的 MIME 类型的库。

    source

    使用扩展名检测 mimetypes

     MimeMagic.by_path('nancy.png')
    

    通过读取文件内容检测mimetype

      MimeMagic.by_magic(File.open('nanc.png'))
    

    【讨论】:

      猜你喜欢
      • 2011-08-06
      • 2020-06-05
      • 2011-06-03
      • 2012-10-09
      • 2014-02-20
      • 1970-01-01
      • 2023-03-13
      • 2021-08-09
      相关资源
      最近更新 更多