fangtingting
12/13/2017 - 8:56 AM

文件操作通用方法

通用的上传附件的方法,返回文件信息

class FileManager
  class << self
    def upload_files(file,root_path,old_file=nil)
      file_hash = {origin_name: file.original_filename,file_size: file.size}
      ext_name = file.original_filename.split('.').last
      time_dir = Time.now.strftime("%Y_%m/")
      if old_file.present?
        new_filename = old_file
      else
        new_filename = time_dir + Time.now.strftime("%d%H%M%S") + "." + ext_name
      end
      # 创建目录
      Dir.mkdir(root_path) unless File.exists?(root_path)
      Dir.mkdir(root_path + time_dir) unless File.exists?(root_path + time_dir)
      # 写入文件
      File.open(root_path + new_filename,"wb"){|f| f.write(file.read)}
      return file_hash.merge!(file_name: new_filename)
    end
  end
end