Search code examples
javascriptjqueryruby-on-railsrubyjquery-file-upload

JQuery File Upload in Rails - Form still sending HTML requests?


I'm trying to do an asynchronous upload using the following form, but micropost#create is responding to an HTML request. Any advice on how to make my upload form send a JS request?

app/views/shared/_micropost_form.html

<%= form_for @micropost, :html => {:multipart => true} do |f| %>
    <%= f.file_field :picture, :multiple => true, :name => "file_folder[picture]" %>
    <div><%= f.text_area :content, placeholder: "Caption (Optional)", id: "post-micropost-area" %></div>
    <div align="center"><%= f.submit "Post", class: "button postbutton" %></div>
<% end %>

<script>
  $(document).ready(function() {

    var multiple_photos_form = $('#new_file_folder');

    multiple_photos_form.fileupload({dataType: 'script'
        add: function (e, data) {
        types = /(\.|\/)(gif|jpe?g|png|bmp)$/i;
        file = data.files[0];
        if (types.test(file.type) || types.test(file.name)) {
          data.submit();
        }
        else { alert(file.name + " must be GIF, JPEG, BMP or PNG file"); }
      }
    });
  });
</script>

app/assets/javascripts/microposts.coffee

(Page with form is rendered by static_pages#home - could that be important?)

jQuery ->
  $('#micropost_form').fileupload
    dataType: "script"

app/controllers/micropost_controller.rb

 def create 
    @micropost = current_user.microposts.new(micropost_params) 
    @micropost.hashtags = @micropost.content.scan(/#\w+/).flatten.join(", ")

    if @micropost.save
        flash[:success] = "Post Created!"
        respond_to do |format|
          format.html {redirect_to root_url }
          format.js
        end
    else
        @feed_items = Micropost.all.paginate(page: params[:page]).per_page(10)
        respond_to do |format|
          format.html { render 'static_pages/home' }
          format.js
        end
    end
  end

[EDIT]

app/views/microposts/create.js.erb

<% if @micropost.new_record? %>
    alert("Failed to upload <%=j @micropost.errors.full_messages.join(', ').html_safe %>.")
<% else %>
    $('#feed').prepend('<%= j render(@micropost) %>')
<% end %>
$('#micropost_form_div').remove();
$('#new-micropost-link').show();

rails server log

Started POST "/microposts" for 130.95.254.26 at 2015-06-09 07:05:02 +0000
Processing by MicropostsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"vQQhQEqn3Owt3arYsUTG0u8rrm9AabK7p4xq1N5hCY7SVUU+1oqM82kiEpkys8P+ju4OScp3te15hJOK/yiw5A==", "micropost"=>{"picture"=>[#<ActionDispatch::Http::UploadedFile:0x007f5a808e8fc8 @tempfile=#<Tempfile:/home/ubuntu/workspace/sample_app/RackMultipart20150609-8758-26fuon.png>, @original_filename="bitcomet-logo.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"micropost[picture][]\"; filename=\"bitcomet-logo.png\"\r\nContent-Type: image/png\r\n">], "content"=>""}, "commit"=>"Post"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."name" ASC LIMIT 1  [["id", 1]]
Unpermitted parameter: picture
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction

Gems (among others)

gem 'carrierwave',             '0.10.0'
gem 'mini_magick',             '3.8.0'
gem 'jquery-rails', '4.0.3'
gem 'jquery-fileupload-rails'

Solution

  • Try this ......

    <%= form_for @micropost, :html => {:multipart => true} do |f| %>
      <p>
        <%= f.file_field :picture, :multiple => true, :name => "micropost[picture]" %>
      </p>
    <% end %>
    
    <script>
      $(document).ready(function() {
    
        var multiple_photos_form = $('#new_file_folder');
    
        multiple_photos_form.fileupload({dataType: 'script'
            add: function (e, data) {
            types = /(\.|\/)(gif|jpe?g|png|bmp)$/i;
            file = data.files[0];
            if (types.test(file.type) || types.test(file.name)) {
              data.submit();
            }
            else { alert(file.name + " must be GIF, JPEG, BMP or PNG file"); }
          }
        });
      });
    </script>
    

    Hope this will help you.