Rails一个简单的文件上传类,仅上传文件

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#encoding: utf-8
require 'fileutils'
class UploadException < RuntimeError; end
#上传文件
class UploadFile
  def initialize(configs)
    @upload_path = "#{Rails.root}/data"
    @type = @max_size = @random_dir = nil
    configs.each do |key, value|
      if config_keys.include? key
        self.send("#{key}=", value)
      end
    end
    FileUtils.mkdir(@upload_path, mode: 0766) unless File.directory? @upload_path
    FileUtils.chmod(0766, @upload_path) unless File.writable_real?(@upload_path)
    ((0..9).to_a + ('a'..'z').to_a).each &method(:check_and_mkdir) if random_dir?
  end

  def upload(file)
    raise UploadException, '文件不是图片格式' if @type == 'image' && !self.is_image?(file)
    file_size = File.size file.tempfile
    file_name = file.original_filename
    raise UploadException, "文件大小超出限制的大小#{@max_size}" if (@max_size && file_size > @max_size.to_i)
    raise UploadException, "上传目录不是目录或不能写入" unless (File.directory?(@upload_path) && File.writable_real?(@upload_path))
    file_path = generage_file_name file.original_filename
    File.open(file_path, 'wb') do |f|
      f.write file.read
    end
  rescue Exception => e
    raise UploadException, '文件上传失败:' + e.message
  else
    {file_name: file_name, file_size: file_size, file_path: file_path}
  end


  protected

  def generage_file_name(original_filename)
    if original_filename
      filename = SecureRandom.uuid + File.extname(original_filename)
      if File.exist? filename
        generage_file_name(original_filename)
      else
        File.join(random_dir, filename)
      end
    end
  end

  def is_image?(file)
    `file --mime -b #{file.tempfile.path}` =~ /^image/
  end

  def config_keys
    [:upload_path, :max_size, :type, :random_dir]
  end

  def upload_path=(path)
    @upload_path = path
  end

  def max_size=(size)
    @max_size = size
  end

  def type=(type)
    @type = type
  end


  def random_dir=(random_dir)
    @random_dir = random_dir
  end

  def random_dir?
    @random_dir
  end

  def check_and_mkdir(dir)
    dir_name = File.join(@upload_path, dir.to_s)
    Dir.mkdir(dir_name) unless File.directory? dir_name
    File.new(dir_name, 'w').chmod(0766)
  end

  def random_dir
    random_dir? ? File.join(@upload_path, ((0..9).to_a + ('a'..'z').to_a).sample) : @upload_path
  end
end