【问题标题】:Cannot upload images with Dropzone.js | Rails 4 and Paperclip无法使用 Dropzone.js 上传图像 | Rails 4 和回形针
【发布时间】:2015-01-04 02:54:54
【问题描述】:

我正在尝试在我的 Rails 应用中设置 Dropzone 以上传多张图片。 Dropzone 似乎在页面上显示正常,但是当我提交时,正确的 url 没有上传到数据库。 JSON 返回{"message":"success","fileID":"/images/original/missing.png"}。它使用的是 Paperclip 缺失的图片 url。

图片模型

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)

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

【问题讨论】:

    标签: javascript ruby-on-rails paperclip


    【解决方案1】:

    在您的创建方法中,替换:

    fileID: @picture.image.url
    

    与:

    fileID: @picture.id
    

    你需要fileID作为上传的id,这样你就可以在js中将它附加到每张图片的删除按钮上。

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

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

    与:

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

    【讨论】:

      【解决方案2】:

      在您的 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     
      

      结束

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-24
        • 2017-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-25
        相关资源
        最近更新 更多