【问题标题】:Rails 4 - How to have image upload in froala editor with carrierwave?Rails 4 - 如何在带有carrierwave的froala编辑器中上传图片?
【发布时间】:2017-09-30 03:26:32
【问题描述】:

我不知道如何在 froala 编辑器中上传图片。我有carrierwave为我的应用程序的其他部分上传图片到谷歌云存储,现在我想在froala编辑器中上传图片。

这是我到目前为止所做的事情

上传图片

class PostImageUploader < CarrierWave::Uploader::Base

  # Choose what kind of storage to use for this uploader:
   storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "post-image"
  end


  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
   def extension_white_list
     %w(jpg jpeg gif png)
   end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  def filename
   "#{model.id}-#{original_filename}" if original_filename.present?
  end

end

我做了一个帖子图片模型

class PostImage < ActiveRecord::Base
  belongs_to :post
  mount_uploader :image, PostImageUploader
  validate  :image_size

    # Validates the size of an uploaded picture.
    def image_size
      if image.size > 5.megabytes
        errors.add(:picture, "should be less than 5MB")
      end
    end

end

我在后置控制器中创建了 attachdetach 方法,但我不知道在其中放入什么。

 def attach
 end

 def detach
 end

 def image_params
   params.require(:post_image).permit(:image)
 end

为附加和分离方法做了路由,但它们可能是错误的,因为我不确定我是否需要这些方法。

match '/guides/:guide_id/posts/attach' => 'posts#attach', :via => :create, as: :attach_guide_post_image
match '/guides/:guide_id/posts/detach'=> 'posts#detach', :via => :delete, as: :detach_guide_post_image

我的 carriwewave 初始化程序已设置并正在工作(因为我在网站上的其他地方使用它)所以我认为我不需要添加它。而且我认为我不需要添加我的后控制器 newcreate 方法,它们的标准标准。

从这里我去了froala docs for image uploads,但我不知道要输入什么值,我需要哪些值,哪些不需要。我的问题是用大写字母写的 cmets。

 <script>
  $(function() {
    $('.editor')
      .froalaeditor({
        // Set the image upload parameter.
        imageUploadParam: 'image',
        // 1. I'M GUESSING THIS IS THE PARAM PASSED

        // Set the image upload URL.
        imageUploadURL: <%= attach_guide_post_image_path =%>,
        // 2. MADE THIS PATH IN THE ROUTES


        // 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', 'gif']
      })
      .on('froalaEditor.image.beforeUpload', function (e, editor, images) {
        // Return false if you want to stop the image upload.

        //3. SO I PUT ERROR MESSAGE IN THESE?? IF SO SHOULD IT BE A POPUP OR TEXT ON THE SCREEN AND HOW
      })
      .on('froalaEditor.image.uploaded', function (e, editor, response) {
        // Image was uploaded to the server.
      })
      .on('froalaEditor.image.inserted', function (e, editor, $img, response) {
        // Image was inserted in the editor.
      })
      .on('froalaEditor.image.replaced', function (e, editor, $img, response) {
        // Image was replaced in the editor.
      })
      .on('froalaEditor.image.error', function (e, editor, error, response) {
        // Bad link.
        else if (error.code == 1) { ... }

        // No link in upload response.
        else if (error.code == 2) { ... }

        // Error during image upload.
        else if (error.code == 3) { ... }

        // Parsing response failed.
        else if (error.code == 4) { ... }

        // Image too text-large.
        else if (error.code == 5) { ... }

        // Invalid image type.
        else if (error.code == 6) { ... }

        // Image can be uploaded only to same domain in IE 8 and IE 9.
        else if (error.code == 7) { ... }

        // Response contains the original server response to the request if available.
      });
  });
</script>

这就是我得到的。我知道基本的 JS,并且已经使用 Rails 大约 6 个月了,所以我对它相当陌生。我从来没有在 Rails 和 js 中做过这样的事情,也找不到可靠的指南。

以上是我得到的,我卡住了。希望从那里获得一些帮助以使图像上传正常工作。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 carrierwave froala


    【解决方案1】:

    我遇到了同样的问题,决定完全绕过carrierwave,直接上传到S3,如下所示:

          $('.post-editor').froalaEditor({
              toolbarBottom: true,
              toolbarButtons: ['bold', 'italic', 'underline', 'fontFamily', 'fontSize', 'paragraphFormat', 'align', 'formatOL', 'formatUL', 'insertLink', 'insertImage', 'insertVideo'],
              imageUploadToS3: {
                bucket: "<%= @hash[:bucket] %>",
                region: 's3-us-west-1',
                keyStart: "<%= @hash[:key_start] %>",
                callback: function (url, key) {},
                params: {
                  acl: "<%= @hash[:acl] %>", // ACL according to Amazon Documentation.
                  AWSAccessKeyId: "<%= @hash[:access_key] %>", // Access Key from Amazon.
                  policy: "<%= @hash[:policy] %>", // Policy string computed in the backend.
                  signature: "<%= @hash[:signature] %>", // Signature computed in the backend.
                }
              }
            })  
    

    在 config/initializers/AWS_CONFIG.rb 中设置一个初始化器:

    AWS_CONFIG = {
      'access_key_id' => ENV["S3_ACCESS_KEY"],
      'secret_access_key' => ENV["S3_SECRET_KEY"],
      'bucket' => 'froala-bucket',
      'acl' => 'public-read',
      'key_start' => 'uploads/'
    }
    

    在 lib/amazon_signature.rb 中设置亚马逊签名:

    module AmazonSignature
      extend self
    
      def signature
        Base64.encode64(
            OpenSSL::HMAC.digest(
              OpenSSL::Digest.new('sha1'),
              AWS_CONFIG['secret_access_key'], self.policy
            )
          ).gsub("\n", "")
      end
    
      def policy
        Base64.encode64(self.policy_data.to_json).gsub("\n", "")
      end
    
      def policy_data
        {
          expiration: 10.hours.from_now.utc.iso8601,
          conditions: [
            ["starts-with", "$key", AWS_CONFIG['key_start']],
            ["starts-with", "$x-requested-with", "xhr"],
            ["content-length-range", 0, 20.megabytes],
            ["starts-with", "$content-type", ""],
            {bucket: AWS_CONFIG['bucket']},
            {acl: AWS_CONFIG['acl']},
            {success_action_status: "201"}
          ]
        }
      end
    
      def data_hash
        {:signature => self.signature, :policy => self.policy, :bucket => AWS_CONFIG['bucket'], :acl => AWS_CONFIG['acl'], :key_start => AWS_CONFIG['key_start'], :access_key => AWS_CONFIG['access_key_id']}
      end
    end
    

    最后在 PostsController 中调用它:

    before_action :set_hash_for_froala
    
    ...
    
    def set_hash_for_froala
      @hash = AmazonSignature::data_hash
    end
    

    这个视频很有帮助:http://rubythursday.com/episodes/ruby-snack-23-froala-wysiwyg-saving-images-on-amazon-s3

    【讨论】:

    • 这很棒。但我不得不在 Froala 编辑器配置中将 region 更改为 "s3"(在 imageUploadToS3 下)
    【解决方案2】:

    这是我大约一年前做的。 [Setting up Froala WYSIWYG editor with CarrierWave and Rails]。

    我会根据你的情况来回答这个问题。

    您可以将文件保存在您的后期控制器中。我假设模型是您帖子中带有“image”属性的“PostImage”。这是控制器的样子:

    def attach
        @postimage = PostImage.new
        @postimage.image = params[:file]
        @postimage.save
    
        respond_to do |format|
            format.json { render :json => { status: 'OK', link: @postimage.image.url}}
        end 
    end
    

    只需在您的 javascript 初始化程序中调用该方法

    <script>
        $(function() {
            $('.selector').froalaEditor({
                // Set the image upload URL.
                imageUploadURL: '<%= attach_guide_post_image_path =%>.json',
                imageUploadMethod: 'POST'
            })
        }
    </script>
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      如果您使用的是 froala gem,他们会在这里遇到问题https://github.com/froala/wysiwyg-rails/issues/22

      【讨论】:

      • 目前还没有问题。我只是不知道该怎么做。
      【解决方案4】:

      试试这个.....

      在你的 routes.rb 中

      resources :posts do
        collection do
          post :froala_image_upload
        end
      end
      

      在您的 posts_controller.rb 中

      def froala_image_upload
              uploader = PostImageUploader.new
              file = params[:file]
              uploader.store!(file)
              render json: { success: true }
          rescue CarrierWave::IntegrityError => e
            render json: { error: e.message }
      end
      
      **script will look like this ...**
      
      <script>
        $(function() {
          $('.editor')
            .froalaeditor({
              imageUploadParam: 'image',
              imageUploadURL: 'froala_image_upload',
              imageMaxSize: 5 * 1024 * 1024,
              imageAllowedTypes: ['jpeg', 'jpg', 'png', 'gif']
            })
            .on('froalaEditor.image.error', function (e, editor, error, response) {
               // Response contains the original server response to the request if available.
            });
        });
      </script>
      

      希望这对你有用。

      【讨论】:

        猜你喜欢
        • 2018-01-01
        • 2014-11-20
        • 1970-01-01
        • 2017-03-02
        • 2013-01-31
        • 2016-01-19
        • 1970-01-01
        • 2015-07-05
        • 2023-02-11
        相关资源
        最近更新 更多