如何使用Froala编辑器和CoffeeScript上传图像

时间:2018-11-26 09:07:02

标签: javascript ruby-on-rails json coffeescript froala

我想使用this gem通过froala编辑器将图像上传到服务器。为此,我正在遵循此guide。我这样创建了上传控制器:

class UploadController < ApplicationController
  ...
  def upload_image
    if params[:file]
      FileUtils::mkdir_p(Rails.root.join("public/uploads/files"))

      ext = File.extname(params[:file].original_filename)
      ext = image_validation(ext)
      file_name = "#{SecureRandom.urlsafe_base64}#{ext}"
      path = Rails.root.join("public/uploads/files/", file_name)

      File.open(path, "wb") {|f| f.write(params[:file].read)}
      view_file = Rails.root.join("/download_file/", file_name).to_s
      render :json => {:link => view_file}.to_json

    else
      render :text => {:link => nil}.to_json
    end
  end
  ...    
end

并添加了一个Coffee脚本来配置froala编辑器,如下所示:

$('#body').froalaEditor({
    # // Set the image upload URL.
  imageUploadURL: '/upload_image',

  # // Set request type.
  imageUploadMethod: 'POST',

  # // Set max image size to 5MB.
  imageMaxSize: 5 * 1024 * 1024,

  # // Allow to upload PNG and JPG.
  imageAllowedTypes: ['jpeg', 'jpg', 'png'],

    height: 400
    requestHeaders: { 
        'X-CSRF-Token': $('meta[name="csrf-token"]')
    }
});

但是,当尝试上传时,我的Rails控制台出现以下错误:

...
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 11ms (ActiveRecord: 0.0ms)
...       
ActionController::InvalidAuthenticityToken 
(ActionController::InvalidAuthenticityToken):

这是csrf令牌的问题。我不知道如何在发出咖啡请求后在咖啡脚本中添加令牌并捕获它。

停用csrf保护不是很多选择,因为这样做会导致安全漏洞,无论如何我都必须稍后修复。

0 个答案:

没有答案