Vitaliy Nesterenko
Vitaliy Nesterenko

Reputation: 11

Rails 4, NiceEdit, Carrierwave. What should i return on upload request?

I am trying to configure Rails 4 with NicEdit html editor. So i downloaded nicEdit-latest.js and correctly setup it with my rails application. Everything to work fine, except uploading images to own server.

I changed the upload url in nicEdit-latest.js to

 {nicURI:"http://myserver.com:3000/upload/get_image",...}

Then i created upload controller with get image_action.

class UploadController < ApplicationController 
protect_from_forgery with: :null_session #without it controller rises an error

  def get_image
   picture = Picture.new
   picture.image = params[:image]
   picture.save
   render :text => picture.image.url #?
  end

end

I configured the carrierwave gem and created model for storing images.

class Picture < ActiveRecord::Base
  mount_uploader :image,PictureUploader
end

I tried playing in console using pry gem, and successfully saved uploaded image using code like

picture.image = params[:image]

But still i received "Failed to upload image" message. I understand, that client side js is awaiting some kind of response. But i can't figure out what it should be. Please help me.

Upvotes: 1

Views: 405

Answers (1)

seufagner
seufagner

Reputation: 1370

After upload image, respond with:

render json: { upload: { links: { original: @image.image_url } } }

To understand why, download uncompressed version on NicEdit download page and check the lines:

1419..1425 - When upload finish and receives JSON response, it get a 'upload' key and call onUploaded function.

xhr.onload = function() {
      try {
        var res = JSON.parse(xhr.responseText);
      } catch(e) {
        return this.onError();
      }
      this.onUploaded(res.upload);
....

1443..1445 - on onUploaded function, navigates to the key inner object key 'links', attribute 'original'

  onUploaded : function(options) {
    this.removePane();
    var src = options.links.original;
    if(!this.im) {
      this.ne.selectedInstance.restoreRng();
      var tmp = 'javascript:nicImTemp();';
      this.ne.nicCommand("insertImage", src);
      this.im = this.findElm('IMG','src', src);
   }
...

ps. I refer to version 0.9 r24

Upvotes: 2

Related Questions