rails 上传文件

控制器文件

app/controllers/api/v1/order_controller.rb

  def create
    # 从本地读取
    log_dir = File.expand_path(File.join(Rails.root.to_s,'/log/ip04.log'))
    puts "log_dir: #{log_dir}"
    file = File.open(log_dir)
    puts "file: #{file} file.size:#{file.size} #{(file.size.to_f/1024/1024).round(2)}mb"
    puts "File::size?: #{File::size?( log_dir)}"
    puts "File::exist?( path): #{File::exist?( log_dir)}"
    puts "file.atime: #{file.atime}"
    puts "file.log_dir: #{File.extname(log_dir)}"

    # form表单上传
    file = params[:file] #上传的key名为file
    puts "@file #{file}"
    # {"file"=>#<ActionDispatch::Http::UploadedFile:0x00007f3bf09cc510 @tempfile=#<Tempfile:/tmp/RackMultipart20210807-28560-1ld7wxc.txt>, @original_filename="ip1000_v1_res_uniq.txt", @content_type="text/plain", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"ip1000_v1_res_uniq.txt\"\r\nContent-Type: text/plain\r\n">}
    puts "@original_filename #{file.original_filename}"
    puts "@basename #{File::basename(file.original_filename)}"
    puts "@size11 #{	(File::size(file.tempfile).to_f/1024/1024)}mb" #@size11 0.00013637542724609375mb
    puts "@zise22 #{file.size}" #@zise22 143
    puts "11111"
    if  file.size.blank? || !File.extname(file.original_filename).downcase.in?([".txt"])
      render(json:{msg:"file is empty! or is not txt"})
      return
    end
    filename = uploadfile(file)
    puts "filename:#{filename}"
    render(json:{msg:"ok"})
  end

  # 上传文件
  def uploadfile(file)
    if !file.original_filename.empty?
      dir_path = get_upload_dir_path
      #设置目录路径,如果目录不存在,生成新目录
      FileUtils.mkdir_p(dir_path, :mode => 2750) unless File.exist?(dir_path)
      #写入文件
      ##wb 表示通过二进制方式写,可以保证文件不损坏
      filename = "#{Time.now.strftime('%Y%m%d%H%M%S')}_#{file.original_filename}"
      filename_path = dir_path + filename
      File.open(filename_path, "wb") do |f|
        f.write(file.read)
      end
      return filename
    end
  end

  # 上传文件的目录
  def get_upload_dir_path(upload_file_path = "/public/upload/category_statistics/")
    @upload_file_path = "#{Rails.root}#{upload_file_path}"
  end

postman 上传

效果

控制器里获取传参

  # {
  #   "type": "ip"
  # }
  def create2
    # 接收单个参数
    # q = params[:q]
    # 读取所有body 去掉回车换行,方便base64
    str = request.body.read
    puts "str: #{str}"
    if str.blank?
      Rails.logger.error("body内容不能为空")
      return { status: false, error_code: 1, error_msg: "body内容不能为空" }
    end
    # {"type": "ip"}
    body_json = JSON.parse(str)
    p_type = body_json["type"]
    puts "body_json: #{body_json} #{body_json["type"]}"

    case p_type
    when "ip"
      puts "ip"
      # save_ip
      save_parent_cate
    else
      puts "不支持"
      res = { code: 400, msg: "不支持 type:#{p_type}" }
      render(json: res)
    end

  end
[Haima的博客] http://www.cnblogs.com/haima/
posted @ 2021-08-07 10:36  HaimaBlog  阅读(25)  评论(0编辑  收藏  举报