Rails 4 – 如何使用carrierwave在froala编辑器中上传图像?

我仍然坚持要在froala编辑器中进行图像上传。 我有载波工作用于将图像上传到我的应用程序的其他部分的谷歌云存储,现在我想在froala编辑器中上传图像。

这是我到目前为止所做的

发布图像uplaoder

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  5.megabytes errors.add(:picture, "should be less than 5MB") end end end 

我在我的post控制器中制作了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初始化程序设置和工作(因为我在网站上的其他地方使用它)所以我不认为我需要添加它。我不认为我需要添加我的post控制器newcreate方法,他们漂亮库存标准。

从这里我去了froala文档上传图片 ,但我不知道要放入什么值,我需要哪些值,哪些不需要。 我的问题是用大写字母写的评论。

   $(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: , // 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. }); });  

这就是我得到的。 我知道基本的JS并且已经使用了大约6个月的rails,所以我对它很新。 我从未在rails和js中做过这样的事情,也找不到可靠的指南。

以上是我得到的,我被卡住了。 在那里需要做些什么来帮助图片上传工作,我会非常乐意。

我遇到了同样的问题并且决定完全绕过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中设置Amazon签名:

 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 

这段video非常有用: http : //rubythursday.com/episodes/ruby-snack-23-froala-wysiwyg-saving-images-on-amazon-s3

我大约一年前做过这个。 [ 使用CarrierWave和Rails设置Froala WYSIWYG编辑器 ]。

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

您可以将文件保存在post post控制器中。 我假设模型是“PostImage”,你的post中带有“image”属性。 这是控制器看起来像:

 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初始化程序中调用该方法即可

  

希望这可以帮助。

如果您使用的是froala gem,那么这里有一个问题可以解决这个问题https://github.com/froala/wysiwyg-rails/issues/22

试试这个 ……………

在您的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 ...**  

希望这对你有用。