我正在努力实现
Ajax-Upload,用于在我的Rails 3应用程序中上传照片.文件说:
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.
那么,如何在我的控制器中收到原始的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