带有dropzonejs-rails文件上传选项的Hello World Rails应用程序

时间:2018-12-14 12:14:31

标签: ruby-on-rails ruby

遵循了这个简单的hello world并创建了应用https://iridakos.com/tutorials/2013/11/24/saying-hello-world-with-ruby-on-rails.html。然后尝试 使用dropzonejs-rails

添加文件上传
$cat app/controllers/pages_controller.rb
class PagesController < ApplicationController
  def home
    puts "Honey, I'm home!"
  end
end

$ cat  app/views/pages/home.html.erb
<h1>Hello world!</h1>

 <form action="/fileupload" class="dropzone" id="my-awesome-dropzone"> </form>


$ cat config/routes.rb
Rails.application.routes.draw do
  root to: 'pages#home'
end

向Gemfile和application.js添加了dropzonejs-rails

$ grep dropzonejs-rails Gemfile
gem 'dropzonejs-rails'

$ grep dropzone app/assets/javascripts/application.js
//= require dropzone 

在网页上,我可以上传文件,但无法保存。由于我不确定如何提供 那。它像Routing Error No route matches [POST] "/fileupload"

一样出错

如何解决此问题。预先感谢。

编辑:@Vasilisa倾向于将文件存储在文件系统下的某个目录中。 (/ some / path / uploadedfiles)

1 个答案:

答案 0 :(得分:1)

即使像/fileupload这样的东西确实不是RESTful的,您也必须走这条路。

我倾向于这样设置资源:

resources :attachments

具有用于处理上载对象的匹配类。

class Attachment < ApplicationRecord
  has_attached_file :data
end

您还需要一个控制器。

class AttachmentsController < ApplicationController
  before_action :set_attachment, only: :index
  before_action :set_attachment, except: %i[show destroy]

  def index
    render json: { images: @attachments }.to_json
  end

  def create
    if @attachment.update_attributes!(attachment_params)
      render json: { attachment: @attachment }, status: 200
    else
      render json: { error: @attachment.errors }, status: 400
    end
  end

  def show
    render json: { attachment: @attachment }.to_json
  end

  def update
    if @attachment.update_attributes!(attachment_params)
      render json: { attachment: @attachment }.to_json
    else
      render json: { error: @attachment.errors }, status: 400
    end
  end

  def destroy
    if @attachment.destroy
      render json: { message: 'success' }, status: 200
    else
      render json: { message: @attachment.errors }, status: 400
    end
  end
end

这样,您就可以与Rails OOP逻辑保持一致。不过,您的路线将从/fileupload更改为/attachments