rails 2从http post body读取文件

时间:2016-05-18 21:00:01

标签: ruby file-upload ruby-on-rails-2

我正在使用rails 2,我正在尝试从http post请求体中读取文件。

  def get_file_from_request(request, file_name)
    file = Tempfile.new([File.basename(file_name, ".*"), File.extname(file_name)])
    Rails.logger.info "#{request.body.size}" # returns 130
    file.write(request.body.read)
    file
  end

如果我这样做

  

request.inspect

我得到以下信息:

...
"rack.version"=>[1, 2], "rack.input"=>#<PhusionPassenger::Utils::TeeInput:0x0000000d3a6148 @len=130, @socket=nil, @bytes_read=130, @tmp=#<StringIO:0x0000000d3a60d0>>, "rack.errors"=>#<IO:<STDERR>>, "rack.multithread"=>false, "rack.multiprocess"=>true, "rack.run_once"=>false, "rack.url_scheme"=>"http", "rack.hijack?"=>true, "rack.hijack"=>#<Proc:0x0000000d3a5ec8@/data/rbenv/.rbenv/versions/1.9.3-p550/lib/ruby/gems/1.9.1/gems/passenger-4.0.42/lib/phusion_passenger/rack/thread_handler_extension.rb:69 (lambda)>,
...

我的方法有任何明显的问题吗?

有人可以帮助我从请求体中提取文件吗?该文件绝对不是130个字节。它就像3 MB。

编辑:这是控制器类

class Api::PhotosController < Api::BaseController
  before_filter :verify_session, :except => [:new, :show_image]

  def create
    Rails.logger.info "upload photo request: params=#{params.inspect}, request=#{request.inspect}"
...
      file = get_file_from_request(request, params[:file_name])
...
  rescue => e
    Rails.logger.info "Could not upload photo: params=#{params.inspect}, exception=#{e.backtrace}"
    render_error(e)
  end

private

      def get_file_from_request(request, file_name)
        file = Tempfile.new([File.basename(file_name, ".*"), File.extname(file_name)])
        Rails.logger.info "#{request.body.size}" # returns 130
        file.write(request.body.read)
        file
      end
end

1 个答案:

答案 0 :(得分:0)

在Rails 2中,您可能必须使用request.raw_post。这有帮助吗?