I’m working on implementing Ajax-Upload for uploading photos in my Rails 3 app. The documentation says:
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.
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.)
Some additional info:
As I’m configured right now the post is passing these parameters:
Parameters:
{"authenticity_token"=>"...", "qqfile"=>"IMG_0064.jpg"}
… 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'
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: