无法使用Dropzone.js上传图像Rails 4和Paperclip

时间:2015-01-04 02:54:55

标签: javascript ruby-on-rails paperclip

我正在尝试在我的Rails应用中设置Dropzone以上传多个图片。 Dropzone好像出现在页面上,但是当我提交时,正确的url不会上传到数据库。 JSON返回{"message":"success","fileID":"/images/original/missing.png"}。它正在使用Paperclip缺少的图像网址。

图片模型

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

图片控制器

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
    });
});

图片/ _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 %>

日志

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)

我也不确定如何在日志的第二行修复错误,我认为可能是问题。

2 个答案:

答案 0 :(得分:0)

在您的create方法中,替换:

fileID: @picture.image.url

使用:

fileID: @picture.id

您需要将fileID作为上传的ID,以便将其添加到每张图片的删除按钮的js中。

您的控制器中是否还有images: []强的参数?因为我认为它应该只是:image,如果你这样做,那么在你的表单中替换:

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

使用:

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

答案 1 :(得分:0)

在您的JavaScript文件中

$(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");
       }
    }); 

});

你的new.html.erb文件中的

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


控制器中的

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