Does the Ruby on Rails CarrierWave gem work with Ajax?

跟風遠走 提交于 2019-12-21 03:45:56

问题


For some reason using the CarrierWave gem with Ajax doesn't seem to be working for me. Am I doing something wrong? I followed the 253 CarrierWave Railscast well and it works without AJAX but in my application I need to use AJAX. Here is my code:

The params list after selecting a jpeg in the image file field:

Parameters: {"item"=>{"remote_image_url"=>""}}

new.html.erb:

<%= form_for(@item, :url => create_item_path, :html => {:id => "create_item_form", :multipart => true}) do |f| %>
    <p>
      <%= f.file_field :image %>
    </p>
    <p>
      <%= f.label :remote_image_url, "or image URL" %><br />
      <%= f.text_field :remote_image_url %>
    </p>
    <%= f.submit "Save", :id => "save_button" %>
<% end %>

application.js

$("#create_item_form").submit(function() {
    $.ajax({
      type: "POST",
      url: $(this).attr("action"),
      dataType: "script",
      data:  $("#destination_item").sortable('serialize') + "&" + $(this).serialize()
      });
      return false;
});

item.rb

class Item < ActiveRecord::Base
  attr_accessible :description, :image, :remote_image_url
  belongs_to :user
  has_many :item_sub
  mount_uploader :image, ImageUploader
end

schema.rb

  create_table "item", :force => true do |t|
    t.integer  "user_id"
    t.string   "title"
    t.string   "image"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

I have the carrierwave gem in my gemfile and I haven't changed anything in the app/uploaders/image_uploader.rb.

Thanks for all your help!


回答1:


There is nothing that can be done without a using a library like Uploadify. This is because the XMLHttpRequest (AJAX) standard has no support for file uploads. The only way you can really fake this is using an iFrame with Flash. Uploadify is the best of these options, and it has the best documentation. This is what has to be done on the client side (browser). Uploadify really isn't a ruby gem, its a collection of flash and js to allow the browser to 'fake it'.

On the server side, you can use carrierwave to support the uploads, but you need a way to get them there from the client side. Here is an extremely similar question which should give you the instructions that you need.

Rails Carrier Wave with JQuery Uploader

Hope this helps,

Joe




回答2:


You can now upload files through ajax without the use of external libraries by using FormData()

SEE: LINK 1 & LINK 2




回答3:


You can't upload a file via ajax like that. You'll need something like: http://www.uploadify.com/



来源:https://stackoverflow.com/questions/9441933/does-the-ruby-on-rails-carrierwave-gem-work-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!