【问题标题】:Rails 3 get raw post data and write it to tmp fileRails 3 获取原始帖子数据并将其写入 tmp 文件
【发布时间】:2011-01-16 06:26:28
【问题描述】:

我正在努力实现 Ajax-Upload 在我的 Rails 3 应用中上传照片。文档说:

  1. 对于 IE6-8、Opera 和其他旧版本的浏览器,您可以根据需要获取文件 通常使用常规的表单库 上传。

  2. 对于上传带有进度条的文件的浏览器,您需要获取 原始帖子数据并将其写入 文件。

那么,我怎样才能在我的控制器中接收原始发布数据并将其写入 tmp 文件,以便我的控制器可以处理它? (在我的例子中,控制器正在做一些图像处理并保存到 S3。)

一些附加信息:

正如我现在配置的那样,帖子正在传递这些参数:

Parameters:
{"authenticity_token"=>"...", "qqfile"=>"IMG_0064.jpg"}

... CREATE 操作如下所示:

def create
    @attachment = Attachment.new
    @attachment.user = current_user
    @attachment.file = params[:qqfile]
    if @attachment.save!
        respond_to do |format|
            format.js { render :text => '{"success":true}' }
        end
    end
end

...但我收到此错误:

ActiveRecord::RecordInvalid (Validation failed: File file name must be set.):
  app/controllers/attachments_controller.rb:7:in `create'

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3 http-post


【解决方案1】:

这是因为 params[:qqfile] 不是 UploadedFile 对象,而是一个包含文件名的字符串。文件的内容存储在请求的正文中(可使用 request.body.read 访问)。当然,你不能忘记向后兼容,所以你仍然必须支持 UploadedFile。

因此,在您以统一的方式处理文件之前,您必须抓住这两种情况:

def create
  ajax_upload = params[:qqfile].is_a?(String)
  filename = ajax_upload  ? params[:qqfile] : params[:qqfile].original_filename
  extension = filename.split('.').last
  # Creating a temp file
  tmp_file = "#{Rails.root}/tmp/uploaded.#{extension}"
  id = 0
  while File.exists?(tmp_file) do
    tmp_file = "#{Rails.root}/tmp/uploaded-#{id}.#{extension}"        
    id += 1
  end
  # Save to temp file
  File.open(tmp_file, 'wb') do |f|
    if ajax_upload
      f.write  request.body.read
    else
      f.write params[:qqfile].read
    end
  end
  # Now you can do your own stuff
end

【讨论】:

  • 谢谢!这很好用!作为评论,我发现(在您让我走上正确的轨道之后)在我的情况下,至少tmp_file = Tempfile.new(filename) 工作得同样好,同时比# Creating a temp file 注释下的代码更干净一点。两种方式都可以正常工作。谢谢!
  • f.write params[:qqfile].read - 这应该是 f.write params[:qqfile].tempfile.read 否则没有文件被存储
  • 不,不应该,UploadedFile#read 是 UploadedFile#tempfile.read 的快捷方式,因此代码在两种情况下都一样
  • 这是命名tmp文件id = 0 file_template = "#{Rails.root}/tmp/uploaded-%s.#{extension}" tmp_file = file_template % id while File.exists?(tmp_file) id += 1 tmp_file = file_template % id end的更好方法
【解决方案2】:

试试看,添加lib/qq_file.rb:

# encoding: utf-8
require 'digest/sha1'
require 'mime/types'

# Usage (paperclip example)
# @asset.data = QqFile.new(params[:qqfile], request)
class QqFile < ::Tempfile

  def initialize(filename, request, tmpdir = Dir::tmpdir)
    @original_filename  = filename
    @request = request

    super Digest::SHA1.hexdigest(filename), tmpdir
    fetch
  end

  def self.parse(*args)
    return args.first unless args.first.is_a?(String)
    new(*args)
  end

  def fetch
    self.write @request.raw_post
    self.rewind
    self
  end

  def original_filename
    @original_filename
  end

  def content_type
    types = MIME::Types.type_for(@request.content_type)
      types.empty? ? @request.content_type : types.first.to_s
  end
end

在 assets_controller 中输入:

def create
  @asset ||= Asset.new(params[:asset])

  @asset.assetable_type = params[:assetable_type]
  @asset.assetable_id = params[:assetable_id] || 0
  @asset.guid = params[:guid]
  @asset.data = QqFile.parse(params[:qqfile], request)
  @asset.user_id = 0
  @success = @asset.save

  respond_with(@asset) do |format|
    format.html { render :text => "{'success':#{@success}}" }
    format.xml { render :xml => @asset.to_xml }
    format.js { render :text => "{'success':#{@success}}"}
    format.json { render :json => {:success => @success} }
  end
end

javascript:

var photo_uploader = new qq.FileUploader({
  element: document.getElementById('photo-button'),
  multiple: true,
  action: '/assets',
  allowedExtensions: ['png', 'gif', 'jpg', 'jpeg'],
  sizeLimit: 2097152,
  params: {guid: $('#idea_guid').val(), assetable_type: 'Idea', klass: 'Picture', collection: true}
});

【讨论】:

    【解决方案3】:

    另一种解决方案是:

    gem 'rack-raw-upload', :git => 'git://github.com/tb/rack-raw-upload.git'
    

    在 config.ru 中:

     require 'rack/raw_upload'
     use Rack::RawUpload
    

    并在控制器中使用 params[:file]。

    【讨论】:

      【解决方案4】:

      您可以使用 StringIO,而不是创建一些杂乱的临时文件。在此处查看我对 CarrierWave 的回答:https://stackoverflow.com/a/8812976/478354

      【讨论】:

        猜你喜欢
        • 2010-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        • 1970-01-01
        • 2013-04-04
        • 1970-01-01
        • 2012-02-28
        相关资源
        最近更新 更多