rails 2 从 http post 正文读取文件

rails 2 read file from http post body

我正在使用 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

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

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