如何在tinymce-rails中限制上传图片类型?

时间:2016-10-31 09:48:47

标签: ruby-on-rails tinymce-4

我正在使用(Rails 5):

gem 'tinymce-rails', '>= 4.4.0'
gem 'tinymce-rails-imageupload', '~> 4.0.0.beta'

我想以某种方式限制上传图片的文件类型 - 如JPEG,PNG,GIF等。现在用户可以上传任何文件类型(甚至是非图片) - 任何扩展名。

如何正确地做到这一点?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

class TinymceAssetsController < ApplicationController
  def create
    # Take upload from params[:file] and store it somehow...
    # Optionally also accept params[:hint] and consume if needed

    fname = params[:file].original_filename

    ri = fname.rindex(".")    

    if ri && (['gif', 'jpg', 'png', 'jpeg', 'svg'].include? fname[fname.rindex(".")+1..-1])

      image = Image.create file: params[:file]    

      render json: {
        image: {
          url: image.file.url
        }
      }, content_type: "text/html"

    else

      render json: {
        error: {
          message: "Invalid file type. <br>Only .jpg, .jpeg, .png, .gif, .svg allowed"
        }
      }, content_type: "text/html"

    end

  end
end