Rails 3获取原始发布数据并将其写入tmp文件 [英] Rails 3 get raw post data and write it to tmp file

查看:116
本文介绍了Rails 3获取原始发布数据并将其写入tmp文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on implementing Ajax-Upload for uploading photos in my Rails 3 app. The documentation says:



  1. 对于IE6-8,Opera,您获得的其他浏览器的旧版本这个文件就像
    通常使用常规的基于表单的
    上传一样。

  1. For IE6-8, Opera, older versions of other browsers you get the file as you normally do with regular form-base uploads.

对于上传带进度条的文件的浏览器,你会需要获取
原始发布数据并将其写入
文件。

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


那么,如何在控制器中接收原始发布数据并将其写入tmp文件,以便我的控制器可以处理它? (在我的情况下,控制器正在进行一些图像处理并保存到S3。)

So, how can I receive the raw post data in my controller and write it to a tmp file so my controller can then process it? (In my case the controller is doing some image manipulation and saving to S3.)

一些额外的信息:

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

As I'm configured right now the post is passing these parameters:

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

。 ..和CREATE操作如下所示:

... and the CREATE action looks like this:

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

...但我收到此错误:

... but I get this error:

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。

That's because params[:qqfile] isn't a UploadedFile object but a String containing the file name. The content of the file is stored in the body of the request (accessible by using request.body.read). Ofcourse, you can't forget backward compatibility so you still have to support UploadedFile.

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

So before you can process the file in a uniform way you have to catch both cases:

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

这篇关于Rails 3获取原始发布数据并将其写入tmp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆