Reputation: 87210
Is there any easy way how to handle AJAX file upload in Rails? e.g. with a plugin
Upvotes: 15
Views: 22688
Reputation: 11
You can use Jquery Form
//= require jquery.form
in your view (haml sample):
= form_for user, authenticity_token: true, :multipart => true, id: 'user_form' do |f|
= f.label :avatar, t("user.avatar")
= f.file_field :avatar, accept: 'image/png,image/gif,image/jpeg'
= f.submit t(user.new_record? ? 'add' : 'update'), class: 'btn btn-primary', data: {disable_with: t(user.new_record? ? 'adding' : 'updating')}
:javascript
$('#user_form').ajaxForm()
here is Rails app sample https://github.com/serghei-topor/ajax-file-upload-rails-sample
Upvotes: 0
Reputation: 41
It's not really necessary to use some special plugins for that. Easiest way to do ajax picture upload for me was just make form that uploading pictures to act like ajax. For that I use ajaxForm jQuery plugin: http://www.malsup.com/jquery/form/ Than return to js uploaded picture and put it to your page.
So, you should make your form be ajaxForm:
$('#uploader').ajaxForm({dataType: "script",
success: ajaxFormErrorHandler,
error: ajaxFormSuccessHandler
}
controler looks like that:
def add_photo
@photo = PhotosMeasurement.new(params[:user_photo])
respond_to do |format|
if @photo.save
format.json { render :json => @photo}
else
format.json { render :json => nil}
end
end
end
and in ajaxFormSuccessHandler you simply get picture object:
var photo = jQuery.parseJSON(responseText.responseText);
and put photo wherever you like:
target.find('.addPhoto').before(''+
'<input class="imageId" type="hidden" value='+photo.id+' > '+
'<img src='+photo.photo.thumb.url+' alt="Thumb_1"> ');
P.S: Don't really know why but if you return to ajaxForm handler something, it handle that request as ERROR not SUCCESS.
P.P.S: surely jQuery-File-Upload plugin makes more but if you don't need all that, you can use this way.
P.P.P.S: you should have already functional non-ajax file upload for do that =)
Upvotes: 0
Reputation: 7193
JQuery File Upload is very active and versatile file upload widget project.
See the demo here: http://blueimp.github.com/jQuery-File-Upload/
Here's a Gem: http://rubygems.org/gems/jquery.fileupload-rails
The wiki also has Rails examples: https://github.com/blueimp/jQuery-File-Upload/wiki
Upvotes: 4
Reputation: 805
If you're using Rails 3, I've written a plugin that makes AJAX style file uploads relatively trivial to implement.
http://rubygems.org/gems/remotipart
Upvotes: 19