Ruby on Rails AJAX file upload

2020-02-10 13:19发布

Is there any easy way how to handle AJAX file upload in Rails? e.g. with a plugin

4条回答
我想做一个坏孩纸
2楼-- · 2020-02-10 13:35

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

查看更多
唯我独甜
3楼-- · 2020-02-10 13: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 =)

查看更多
4楼-- · 2020-02-10 13:54

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

查看更多
可以哭但决不认输i
5楼-- · 2020-02-10 14:00

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

查看更多
登录 后发表回答