Is there any easy way how to handle AJAX file upload in Rails? e.g. with a plugin
问题:
回答1:
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
回答2:
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
回答3:
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 =)
回答4:
You can use Jquery Form
- download jquery.form.min.js and put it to vendor/assets/javascripts folder
- in your application.js
//= 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