我使用了carrierwave和fog来上传到Amazon S3。这是它的样子,我会跳过fog部分,你可能需要做一些调整。然而,概念很简单。
我使用了angularJS,但是jquery选项应该是这样的。你需要用POST方法定义你的上传路由。
javascript:
<script>
$(function() {
$('.selector').froalaEditor({
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
@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。希望这有所帮助!如果有任何困惑,请告诉我。