简体   繁体   中英

Cannot upload images with Dropzone.js | Rails 4 and Paperclip

I'm trying to setup Dropzone in my Rails app to upload multiple images. Dropzone seems to appear on the page fine, but when I submit, the correct url is not uploaded to the database. The JSON returns {"message":"success","fileID":"/images/original/missing.png"} . It's using Paperclip's missing image url.

Picture Model

class Picture < ActiveRecord::Base

    belongs_to :album

    has_attached_file :image,
                      :path => ":rails_root/public/images/:id/:filename",
                      :url  => "/images/:id/:filename",
                                        :styles => { :small => "160x160>" }

    do_not_validate_attachment_file_type :image

end

Pictures Controller

def create
    @picture = Picture.create(picture_params)
    if @picture.save
      # send success header
      render json: { message: "success", fileID: @picture.image.url }, :status => 200
    else
      #  you need to send an error header, otherwise Dropzone
      #  will not interpret the response as an error:
      render json: { error: @picture.errors.full_messages.join(',')}, :status => 400
    end
  end

pictures.js

$(document).ready(function(){
    // disable auto discover
    Dropzone.autoDiscover = false;

    // grap our upload form by its id
    $("#new_picture").dropzone({
        // restrict image size to a maximum 1MB
        maxFilesize: 1,
        // changed the passed param to one accepted by
        // our rails app
        paramName: "picture[image]",
        // show remove links on each image upload
        addRemoveLinks: true
    });
});

pictures/_form

<%= simple_form_for(@picture, :html => {:class => 'dropzone', multipart: true}) do |f| %>

    <%= f.error_notification %>

    <div class="form-inputs">
      <%= f.input :title %>
      <%= f.input :description %>
      <%= f.input :album_id %>
    </div>

    <%= f.label :pictures, :class => 'control-label' %>
    <div class="controls">

      <%= f.file_field "images[]"%>
    </div>

    <div class="form-actions">
      <%= f.button :submit %>
    </div>
<% end %>

Logs

Started POST "/pictures" for ::1 at 2015-01-03 21:49:10 -0500
Value for params[:picture][:images] was set to nil, because it was one of [], [null] or [null, null, ...]. Go to http://guides.rubyonrails.org/security.html#unsafe-query-generation for more information.
Processing by PicturesController#create as JSON
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"oM1TCKtz7RGVdJ20qmlYVMXfMuSFylQbRZPkMWlBir8=", "picture"=>{"title"=>"", "description"=>"", "album_id"=>"", "images"=>nil, "image"=>#<ActionDispatch::Http::UploadedFile:0x007ff7d953d7b0 @tempfile=#<Tempfile:/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/RackMultipart20150103-50729-10fo75i>, @original_filename="Space.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"picture[image]\"; filename=\"Space.jpeg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Create Picture"}
Unpermitted parameters: images
Command :: file -b --mime '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-eoe314.jpeg'
Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-1tu8uv1.jpeg[0]' 2>/dev/null
Command :: identify -format %m '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-1tu8uv1.jpeg[0]'
Command :: convert '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-1tu8uv1.jpeg[0]' -auto-orient -resize "160x160>" '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-1tu8uv120150103-50729-5ctpcf'
Command :: file -b --mime '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-1tu8uv120150103-50729-5ctpcf'
   (0.3ms)  BEGIN
Command :: file -b --mime '/var/folders/_q/9phh0t7s2xnfx_qy82w59thm0000gn/T/d511f8439ecde36647437fbba67a439420150103-50729-113dzu5.jpeg'
  SQL (0.6ms)  INSERT INTO "pictures" ("created_at", "description", "image_content_type", "image_file_name", "image_file_size", "image_updated_at", "title", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"  [["created_at", "2015-01-04 02:49:10.698173"], ["description", ""], ["image_content_type", "image/jpeg"], ["image_file_name", "Space.jpeg"], ["image_file_size", 344179], ["image_updated_at", "2015-01-04 02:49:10.397270"], ["title", ""], ["updated_at", "2015-01-04 02:49:10.698173"]]
   (16.6ms)  COMMIT
   (0.3ms)  BEGIN
   (0.3ms)  COMMIT
Completed 200 OK in 359ms (Views: 0.2ms | ActiveRecord: 18.1ms)

I'm also not sure how to fix the error in the second line of the log, which I think might be the problem.

In your create method, replace:

fileID: @picture.image.url

with:

fileID: @picture.id

you will need fileID to be the id of the upload so you can append it in the js to the delete button of each image.

also do you have images: [] in strong params in your controller? because I believe it should just be :image , also if you do that then in your form replace:

<%= f.file_field "images[]"%>

with:

<%= f.file_field :image, multiple: true %>

In Your JavaScript File

$(document).ready(function()
{
Dropzone.autoDiscover = false;
$("#new_upload").dropzone({
    // restrict image size to a maximum 1MB
    maxFilesize: 10,
    // changed the passed param to one accepted by
    // our rails app
    paramName: "upload[image]",
    // show remove links on each image upload
    addRemoveLinks: true,
    // if the upload was successful
    success: function(file, response){
        // find the remove button link of the uploaded file and give it an id
        // based of the fileID response from the server
        $(file.previewTemplate).find('.dz-remove').attr('id', response.fileID);
        // add the dz-success class (the green tick sign)
        $(file.previewElement).addClass("dz-success");
       }
    }); 

});

in your new.html.erb file

<%= f.file_field :image %><br>
<%= f.submit "Upload" %>


in your controller

def create
@upload = Upload.create(upload_params)
if @upload.save
  # send success header
  render json: { message: "success", fileID: @upload.id }, :status => 200
else
  #  you need to send an error header, otherwise Dropzone
  #  will not interpret the response as an error:
  render json: { error: @upload.errors.full_messages.join(',')}, :status => 400
end     

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM