7

I'm getting [object Object] on my thumbnails (the background image is the area where you can click on to upload photos... I'm not sure how to load up the normal box similar to the example in http://www.dropzonejs.com/)

enter image description here

View

<%= 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

controller

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

model

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/

EDIT

Posting controller per comment requets

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
hellomello
  • 8,219
  • 39
  • 151
  • 297
  • I've checked the site; there's only one example at the top. I think it is not configured with thumbnail.. where's the example u see? – songyy Jul 21 '15 at 06:10
  • @songyy what do you mean? There's a 'Try It Out' section. Upload any image and you'll see thumbnails populate – hellomello Jul 21 '15 at 06:15
  • after upload I can see a thumbnail, but here's nothing popup when I hover onto the thumbnail image. Is there anything I missed out? – songyy Jul 21 '15 at 06:17
  • @songyy yeah because that example is working fine. My issue here is that my images are returning [object Object] and not uploading correctly – hellomello Jul 21 '15 at 06:18
  • Sorry I still don't quite get.. isn't the thumbnail image shown..? I.e., I can see 3 blocks of images, I assume it is the background image? – songyy Jul 21 '15 at 06:20
  • @songyy Yes, the thumbnails are showing, but its not uploading correctly. For some reason, the thumbnail (when hovered) displays errors, and in my case, its displaying [object Object]. – hellomello Jul 21 '15 at 06:23
  • Are there any errors in your browser's javascript console when you attempt the upload? – Musannif Zahir Jul 22 '15 at 11:28
  • @hellomello can you please post the controller code as well? I also faced same issue some week ago – Bibek Sharma Jul 22 '15 at 12:09
  • @bipashant hi, I added controller – hellomello Jul 22 '15 at 13:42
  • @MusannifZahir naw, just that object object error in the thumbnail when I hover over it – hellomello Jul 22 '15 at 13:42
  • Can you include `project_params` method? – Pavan Jul 22 '15 at 18:20
  • Sorry, I've been changing the params, but everything should be project, instead of trip. I modified this for stackoverflow purposes only. – hellomello Jul 22 '15 at 21:19

1 Answers1

8

In Rails You can't post data without using form. Rails verifies the CSRF token for each request unless token_authentication is turned off.In your code, you initialized dropzone using div ID. So server can't verify your authenticity 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.

So initialize your dropzone using id of the form.

HTML code

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

and your Javascript should like this

   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;
                });
             }
        });
abhinavmsra
  • 666
  • 6
  • 21
Bibek Sharma
  • 3,210
  • 6
  • 42
  • 64
  • I'm getting like a `POST http://localhost:3000/projects 422 (Unprocessable Entity)` – hellomello Jul 24 '15 at 06:56
  • Are you using nested form? It is the issue of dropzone you can't use in nested form because dropzone directly submit its own form while we choose the image – Bibek Sharma Jul 24 '15 at 08:35
  • stackoverflow.com/questions/27206296/ruby-on-rails-image-upload-with-dropzone-in-nested-form – Bibek Sharma Jul 24 '15 at 09:04
  • Now, when I try to upload images, it just disappears right away, and I get this error now: `Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)`. – hellomello Jul 24 '15 at 13:40
  • @hellomello are you using nestedform? or please post the server log – Bibek Sharma Jul 24 '15 at 14:08
  • No, stripped everything bare so my field is not nested. But I don't get where the records are saved, if its not nested? `:beautiful_image` is a column within the `project` model. So if there's multiple images, how does it save in that record? Also, when I'm testing this, in my log, I get `Unpermitted parameter: beautiful_image`, also, it doen't store anything... all the parameters are getting `""`, empty strings. – hellomello Jul 24 '15 at 18:37
  • @hellomello I wonder how can you save multiple images on a single column. also you have project_images_attributes: [:id, :project_id, :photo, :_destroy]) on your project_params. – Bibek Sharma Jul 24 '15 at 18:42
  • I have a `ProjectImages` model, and a regular `Project` model that has `beautiful_images` as a column. So I was just asking how saving images work without nested fields? Because don't you need nested fields to save multiple files so a project can be related to multiple images based on (ie: `project_id`) – hellomello Jul 25 '15 at 03:33
  • Yes, You're right. Then why you need beautiful_images as column in project. You can directly achieve it from @project.project_images. – Bibek Sharma Jul 25 '15 at 03:50