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

前端之家收集整理的这篇文章主要介绍了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.)

一些额外的信息:

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

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

…和CREATE操作如下所示:

  1. def create
  2. @attachment = Attachment.new
  3. @attachment.user = current_user
  4. @attachment.file = params[:qqfile]
  5. if @attachment.save!
  6. respond_to do |format|
  7. format.js { render :text => '{"success":true}' }
  8. end
  9. end
  10. end

…但是我得到这个错误

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

解决方法

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

所以在你可以统一的方式处理这个文件之前,你必须抓住这两种情况:

  1. def create
  2. ajax_upload = params[:qqfile].is_a?(String)
  3. filename = ajax_upload ? params[:qqfile] : params[:qqfile].original_filename
  4. extension = filename.split('.').last
  5. # Creating a temp file
  6. tmp_file = "#{Rails.root}/tmp/uploaded.#{extension}"
  7. id = 0
  8. while File.exists?(tmp_file) do
  9. tmp_file = "#{Rails.root}/tmp/uploaded-#{id}.#{extension}"
  10. id += 1
  11. end
  12. # Save to temp file
  13. File.open(tmp_file,'wb') do |f|
  14. if ajax_upload
  15. f.write request.body.read
  16. else
  17. f.write params[:qqfile].read
  18. end
  19. end
  20. # Now you can do your own stuff
  21. end

猜你在找的Ruby相关文章