2016-05-30 32 views
8

Utknąłem na temat tego, co zrobić, aby załadować obraz w edytorze froala. Mam działającą dla Ciebie przesyłkę do wysyłania zdjęć do Google Cloud Storage dla innych sekcji mojej aplikacji, a teraz chcę mieć również możliwość załadowania zdjęć do edytora froala.Rails 4 - Jak załadować obraz w edytorze froala z carrierwave?

Oto co zrobiłem do tej pory

obraz po 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 

zrobiłem model po obrazu

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 

zrobiłem attach i detach metody w moim kontroler postu ale nie wiem, co w nich umieścić.

def attach 
end 

def detach 
end 

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

Stworzyłem trasy do metod dołączania i odłączania, ale mogą one być błędne, ponieważ nie jestem pewien, czy nawet potrzebuję tych metod.

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 

mój carriwewave inicjująca jest ustawiony i działa (bo używam go w innych miejscach na miejscu), więc nie sądzę, że trzeba dodać go. I nie sądzę, muszę dodać mój kontroler pocztowy new i create metody, ich ładny standard.

Stąd poszedłem do froala docs for image uploads, ale nie wiem, jakie wartości umieścić i które potrzebuję, a których nie potrzebuję. Moje pytania to komentarze napisane wielkimi literami.

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

Oto, co mam. Znam podstawowe JS i używam szyn przez około 6 miesięcy, więc jestem całkiem nowy w tym. Nigdy nie robiłem czegoś takiego w szynach i js i nie mogę znaleźć na nim solidnego przewodnika.

Powyżej jest to, co mam i utknąłem. Chciałbym uzyskać pomoc dotyczącą tego, co należy zrobić, aby przesyłać zdjęcia.

Odpowiedz

0

Spróbuj ...............

w twojej routes.rb

resources :posts do 
    collection do 
    post :froala_image_upload 
    end 
end 

W swojej 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> 

Mam nadzieję, że to zadziała.

+0

Nie działa, usługa się nie zmieniła –

3

zmagałem się z tym samym problemem i postanowił ominąć carrierwave całkowicie i po prostu przesłać bezpośrednio do S3 następująco:

 $('.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. 
      } 
      } 
     }) 

Konfigurowanie inicjatora w config/inicjalizatory/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/' 
} 

Skonfiguruj podpis Amazon w 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 

I wreszcie nazwać w PostsController:

before_action :set_hash_for_froala 

... 

def set_hash_for_froala 
    @hash = AmazonSignature::data_hash 
end 

Ten film był bardzo pomocny: http://rubythursday.com/episodes/ruby-snack-23-froala-wysiwyg-saving-images-on-amazon-s3

+1

To jest świetne. Ale musiałem zmienić 'region' na' "s3" 'w konfiguracji edytora Froala (pod' imageUploadToS3') – sequielo

2

Zrobiłem to o rokiem temu. [Setting up Froala WYSIWYG editor with CarrierWave and Rails].

Postaram się odpowiedzieć na to na podstawie Twojej sprawy.

Możesz zapisać plik w akcji dołączyć do swojego kontrolera pocztowego. Zakładam, że model to "PostImage" z atrybutem "image" ze swojego posta. Jest to kontroler wygląda następująco:

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 

Wystarczy wywołać metodę w JavaScript inicjatora

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

nadzieję, że to pomaga.