使用CarrierWave和Rails设置Froala所见即所得编辑器

4

我一直在尝试将Froala与我的Rails应用完全配合使用。我有一种类似博客的应用程序,每篇文章都有相关联的图片。

class Post < ActiveRecord::Base
has_many :images
accepts_nested_attributes_for :images

class Image < ActiveRecord::Base
belongs_to :post
mount_uploader :image, ImageUploader

我正在尝试弄清楚如何在Froala中使其起作用。 我可以在Froala配置中设置上传URL,但我不知道应该是什么。

<script>
  $(function() {
    $('.selector').froalaEditor({
      // Set the image upload URL.
      imageUploadURL: '????',

      imageUploadParams: {
        id: 'my_editor'
      }
    })
  });
</script>

我已经研究了一整天,尝试了我能想到的所有方法。非常感谢任何帮助。谢谢。


你解决了吗?我也卡在这个问题上了。https://dev59.com/M5ffa4cB1Zd3GeqP9Ine - Rob
您可以在下面的答案中找到上传URL和实现示例。 - Nate Cheng
2个回答

6
我使用了carrierwave和fog来上传到Amazon S3。这是它的样子,我会跳过fog部分,你可能需要做一些调整。然而,概念很简单。
我使用了angularJS,但是jquery选项应该是这样的。你需要用POST方法定义你的上传路由。
javascript:
<script>
    $(function() {
        $('.selector').froalaEditor({
            // Set the image upload URL.
            imageUploadURL: '/attachment/upload.json',
            imageUploadMethod: 'POST'
        })
    }
</script>

那么您需要实现/attachment/upload.json接口。在Rails中,
-- attachment.rb
class Attachment < ActiveRecord::Base
    mount_uploader :picture, PictureUploader
end

因为这是ajax调用,所以在提交时您需要在控制器中处理CSRF令牌验证。此示例将跳过验证:因此在您的控制器中添加skip_before_filter:verify_authenticity_token。如果您不想跳过验证,则需要在Froala初始化中传递参数,如imageUploadParams:{'authenticity_token':your csrf token}。现在让我们来看看Rails部分。

-- attachments_controller.rb
class AttachmentsController < ApplicationController
    skip_before_filter :verify_authenticity_token
  ...


    def upload
        # The Model: Attachment, created below.

        @attachment = Attachment.new
        @attachment.picture = params[:file]
        @attachment.save

        respond_to do |format|
            format.json { render :json => { status: 'OK', link: @attachment.picture.url}}
        end
    end
    ...

end

使用Rails生成一个PictureUploader并在控制台中创建模型。
rails generate uploader Picture
rails g model attachment picture:string
rake db:migrate

在你的route.rb文件中,设置到你的controller#method的路由。

post 'attachment/upload' => 'attachments#upload'

所以你将拥有一个通过POST请求的路由/attachment/upload,并且它调用了attachment#upload。希望这有所帮助!如果有任何困惑,请告诉我。

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接