ruby-on-rails – Rails 3获取原始帖子数据并将其写入tmp文件

我正在努力实现 Ajax-Upload,用于在我的Rails 3应用程序中上传照片.文件说:
  1. For IE6-8,Opera,older versions of other browsers you get the file as you
    normally do with regular form-base
    uploads.

  2. For browsers which upload file with progress bar,you will need to get the
    raw post data and write it to the
    file.

那么,如何在我的控制器中收到原始的post数据并将其写入一个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'

解决方法

那是因为params [:qqfile]不是一个UploadedFile对象,而是包含文件名的String.文件内容存储在请求的正文中(可以使用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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...