如何将图像上传到Rails文章

时间:2017-09-26 20:47:08

标签: ruby-on-rails ruby image trix

我正在Rails中重建博客,并且我正在使用Trix作为我的文本编辑器。我有关于Trix设置的所有内容。我可以拖动图像并将其放入Trix文本编辑器中,当我单击“创建文章”时,我没有错误。但是当我去看文章时,没有图像。这似乎是一个非常容易解决的问题。

show.html.erb

<h1>Showing Blog Posts</h1>

<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @article.text.html_safe %>
</p>

<%= link_to 'Back', articles_path %>

article_controller.rb

class ArticlesController < ApplicationController
    def index
       @articles = Article.all 
    end

    def show
       @article = Article.find(params[:id]) 
    end

    def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_params)

        if @article.save
          redirect_to @article
        else
          render 'new'
        end
    end

    def update 
       @article = Article.find(params[:id])

       if @article.update(article_params)
           redirect_to @article
       else
           render 'edit'
       end
    end

    private
        def article_params
            params.require(:article).permit(:title, :text)
        end
end

articles.coffee (将图像上传到Trix编辑器的代码)

$ ->
  document.addEventListener 'trix-attachment-add', (event) ->
    attachment = event.attachment
    if attachment.file
      return sendFile(attachment)
    return

  document.addEventListener 'trix-attachment-remove', (event) ->
    attachment = event.attachment
    deleteFile attachment

  sendFile = (attachment) ->
    file = attachment.file
    form = new FormData
    form.append 'Content-Type', file.type
    form.append 'image[image]', file
    xhr = new XMLHttpRequest
    xhr.open 'POST', '/images', true

    xhr.upload.onprogress = (event) ->
      progress = undefined
      progress = event.loaded / event.total * 100
      attachment.setUploadProgress progress

    xhr.onload = ->
      response = JSON.parse(@responseText)
      attachment.setAttributes
        url: response.url
        image_id: response.image_id
        href: response.url

    xhr.send form

  deleteFile = (n) ->
    $.ajax
      type: 'DELETE'
      url: '/images/' + n.attachment.attributes.values.image_id
      cache: false
      contentType: false
      processData: false

  return

0 个答案:

没有答案