ruby-on-rails - Ruby on Rails : Dropzone js, 正在获取 [object Object],但为什么呢?

标签 ruby-on-rails ruby ruby-on-rails-4 paperclip dropzone.js

我的缩略图上出现了 [object Object](背景图像是您可以点击上传照片的区域...我不确定如何加载类似于 http://www.dropzonejs.com/ 中示例的普通框)

enter image description here

查看

<%= simple_form_for @project do |f| %>

  <div class="dropzone dz-clickable dz-square" id="mydrop">
    <div class="dz-default dz-message" data-dz-message=""></div>
    <div id="bi_previews"></div>
    <div class="fallback">
      <%= f.file_field :beautiful_image %></div>
    </div>
  </div>

<% end %>

CoffeeScript

$(document).on 'ready page:load', ->
  Dropzone.autoDiscover = false
  $('div#mydrop').dropzone 
    url: '/projects'
    previewsContainer: "#bi_previews"
    headers: "X-CSRF-Token" : $('meta[name="csrf-token"]').attr('content')
    paramName: "project[beautiful_image]"
    init: ->
      @on 'success', (file, json) ->
      @on 'addedfile', (file) ->
      @on 'drop', (file) ->
        alert 'file'
        return
      return

routes.rb

Rails.application.routes.draw do
  devise_for :users
  resources :projects

控制者

def project_params
  params.require(:project).permit(
    :user_id, :beautiful_image, :title_name, :remove_project_images_files, project_images_files: [],
    project_images_attributes: [:id, :project_id, :photo, :_destroy]).merge(user_id: current_user.id)
end

型号

has_attached_file :beautiful_image, :styles => { :large => "800x800>", :medium => "500x500>", :thumb => "150x150#" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :beautiful_image, content_type: /\Aimage\/.*\Z/

编辑

根据评论请求发布 Controller

def new
  @project = Project.new
  @gear = Gear.new
  @project.gears.build
  @project.project_images.build
end

def edit
  @project = Project.find(params[:id])
end

def create
  @project = Project.new(project_params)

  respond_to do |format|
    if @project.save
      format.html { redirect_to @project, notice: 'Project was successfully created.' }
      format.json { render :show, status: :created, location: @project }
    else
      format.html { render :new }
      format.json { render json: @project.errors, status: :unprocessable_entity }
    end
  end
end

最佳答案

在 Rails 中,您不能在不使用表单的情况下发布数据。 Rails 验证每个请求的 CSRF token ,除非 token_authentication 被关闭。在您的代码中,您使用 div ID 初始化了 dropzone。所以服务器无法验证您的真实性 token

The ApplicationController called protect_from_forgery, as appropriate. All of the controllers inherited from ApplicationController, and it appeared that there were no CSRF vulnerabilities. Through dynamic analysis, however, I discovered that the application was, in fact, vulnerable to CSRF.

所以使用表单的 id 初始化你的 dropzone。

HTML代码

<%= simple_form_for @project, class: 'dropzone', id: 'project-form' do |f| %>
            <div class="fallback">
              <%= f.file_field :beautiful_image, multiple: true %>
            </div>
 <% end %>

你的 Javascript 应该是这样的

   var objDropZone;
   Dropzone.autoDiscover = false;
   $("#project-form").dropzone({
            acceptedFiles: '.jpeg,.jpg,.png',
            maxFilesize: 5, //In MB
            maxFiles: 5,
            addRemoveLinks: true,
            removedfile: function (file) {
                if (file.xhr.responseText.length > 0) {
                    var fileId = JSON.parse(file.xhr.responseText).id;
                        $.ajax({
                        url: '/projects/' + fileId,
                        method: 'DELETE',
                        dataType: "json",
                        success: function (result) {
                           console.log('file deleted successfully');
                            var _ref;
                            return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;

                        },
                        error: function () {
                          console.log('error occured while deleteing files');
                        }

                    });
                }

            },
            init: function () {
                objDropZone = this;

                this.on("success", function (file, message) {
                    console.log('file uploaded successfully')
                });

                this.on("error", function (file, message) {
                    var _ref;
                    return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
                });
             }
        });

关于ruby-on-rails - Ruby on Rails : Dropzone js, 正在获取 [object Object],但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31496171/

相关文章:

ruby-on-rails - 如何访问 View 中的实例变量 id

ruby-on-rails - rails : How to ensure clean state for test database?

ruby-on-rails - 在用户等待时处理大量数据的最佳实践(在 Rails 中)?

ruby - Ruby 中 .next 和 .succ 的区别

ruby - 使用 jemalloc 和 rbenv 编译 Ruby 2.2 的正确方法?

ruby - Rails - 如何使用 where() 查找特定列值为 nil 的所有行

ruby-on-rails - 为什么当 rails redirect_to 成功调用新的 url 时浏览器的地址没有改变?

ruby-on-rails - 调整 ruby gem 以进行代码阅读的最佳方法是什么

ruby-on-rails - 如何使此正则表达式规则不区分大小写

ruby-on-rails - 解决 PG::GroupingError: ERROR