2016-05-30 40 views
8

我被困在froala編輯器中進行圖片上傳的操作。我有carrierwave工作上傳圖片到谷歌雲存儲我的應用程序的其他部分,現在我想在froala編輯器中也有圖片上傳。Rails 4 - 如何使用carrierwave在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 < 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,但我不知道輸入什麼值,哪些是我需要的,哪些是我不需要的。我的問題是用大寫字母寫的評論。

<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,並且已經使用了大約6個月的rails,所以對它來說相當新穎。我從來沒有在rails和js中做過這樣的事情,也找不到一個可靠的指南。

上面是我得到和我卡住了。會喜歡一些幫助,從那裏需要做什麼,以獲得圖像上傳工作。

回答

0

試試這個問題...............

在你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> 

希望這會爲你工作。

+0

不工作,發球沒變 –

3

我掙扎着同樣的問題,並決定完全繞過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. 
      } 
      } 
     }) 

設置一個初始的配置/初始化/ 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中設置Amazon簽名。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

+1

這太好了。但是我必須在Froala編輯器配置中將'region'換成''s3「'(在'imageUploadToS3'下面) – sequielo

2

我做了這個關於年前。 [Setting up Froala WYSIWYG editor with CarrierWave and Rails]。

我會盡量根據您的情況來回答這個問題。

您可以將動作附件中的文件保存在您的後控制器中。我假設你的帖子中的模型是帶有「圖像」屬性的「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> 

希望這有助於。

相關問題