Ruby on Rails-파일 업로드

사이트 방문자가 서버에 파일을 업로드하기를 원하는 요구 사항이있을 수 있습니다. Rails를 사용하면 이러한 요구 사항을 매우 쉽게 처리 할 수 ​​있습니다. 이제 우리는 간단하고 작은 Rails 프로젝트를 진행할 것입니다.

평소와 같이 새로운 Rails 애플리케이션으로 시작하겠습니다. testfile. 간단한 rails 명령을 사용하여 응용 프로그램의 기본 구조를 만들어 보겠습니다.

tp> rails new testfile

응용 프로그램 개발을 시작하기 전에 아래와 같이 gem 파일을 설치해야합니다.

gem install carrierwave
gem install bootstrap-sass

gemfile을 열고 다음 이미지와 같이 하단에 다음 두 개의 gem을 추가합니다.

gem 파일에 gem을 추가 한 후 콘솔에서 다음 명령을 실행해야합니다.

bundle install

모델 생성

아래 그림과 같이 이름과 첨부 파일로 두 개의 문자열이있는 모델을 만들어야합니다.

rails g model Resume name:string attachment:string

아래와 같이 데이터베이스 마이그레이션을 생성해야합니다.

rake db:migrate

아래와 같이 컨트롤러를 생성해야합니다.

rails g controller Resumes index new create destroy

큰! 이제 기본 구조가 설정되었습니다. 이제 업 로더를 만들어야합니다. 업 로더는 carrierwave gem에서 왔으며 파일 처리 방법을 carrierwave에 알려줍니다. 즉, 모든 파일 처리 기능이 포함되어 있습니다. 명령을 실행하여 아래와 같이 업 로더를 만듭니다.

rails g uploader attachment

이제 이력서 모델을 열고 아래와 같이 업 로더를 호출합니다. 이력서 모델이 app / models / resume.rb에 배치되었습니다-

class Resume < ActiveRecord::Base
   mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model.
   validates :name, presence: true # Make sure the owner's name is present.
end

컨트롤러에서 작업하기 전에 아래와 같이 config / routes.db를 수정해야합니다.

CarrierWaveExample::Application.routes.draw do
   resources :resumes, only: [:index, :new, :create, :destroy]
   root "resumes#index"
end

아래와 같이 컨트롤러를 편집 해 보겠습니다.

class ResumesController < ApplicationController
   def index
      @resumes = Resume.all
   end
   
   def new
      @resume = Resume.new
   end
   
   def create
      @resume = Resume.new(resume_params)
      
      if @resume.save
         redirect_to resumes_path, notice: "The resume #{@resume.name} has been uploaded."
      else
         render "new"
      end
      
   end
   
   def destroy
      @resume = Resume.find(params[:id])
      @resume.destroy
      redirect_to resumes_path, notice:  "The resume #{@resume.name} has been deleted."
   end
   
   private
      def resume_params
      params.require(:resume).permit(:name, :attachment)
   end
   
end

css file.css 파일에 부트 스트랩 구현을 추가해 보겠습니다. app / assets / stylesheets / resumes.css.scss에있을 수 있습니다.

@import "bootstrap";

이제 app / views / layouts / application.html.erb를 열고 아래와 같이 코드를 추가하십시오.

<!DOCTYPE html>
<html>
   
   <head>
      <title>Tutorialspoint</title>
      <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
      <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
      <%= csrf_meta_tags %>
   </head>
   
   <body>
      <div class = "container" style = "padding-top:20px;">
         <%= yield %>
      </div>
   </body>

</html>

이제 아래와 같이 인덱스 뷰를 설정해야합니다.

<% if !flash[:notice].blank? %>
   <div class = "alert alert-info">
      <%= flash[:notice] %>
   </div>
<% end %>

<br />

<%= link_to "New Resume", new_resume_path, class: "btn btn-primary" %>
<br />
<br />

<table class = "table table-bordered table-striped">
   <thead>.
      <tr>
         <th>Name</th>
         <th>Download Link</th>
         <th> </th>
      </tr>
   </thead>
   
   <tbody>
      <% @resumes.each do |resume| %>
         
         <tr>
            <td><%= resume.name %></td>
            <td><%= link_to "Download Resume", resume.attachment_url %></td>
            <td><%= button_to "Delete",  resume, method: :delete, class: "btn btn-danger", confirm: "Are you sure that you wish to delete #{resume.name}?" %></td>
         </tr>
         
      <% end %>
   </tbody>
   
</table>

이제 new.html.erb를 편집하고 양식 코드를 추가합니다.

<% if [email protected]? %>
   <div class = "alert alert-error">
      
      <ul>
         <% @resume.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
         <% end %>
      </ul>
      
   </div>
<% end %>

<div class = "well">
   <%= form_for @resume, html: { multipart: true } do |f| %>
      <%= f.label :name %>
      <%= f.text_field :name %>
      <%= f.label :attachment %>
      <%= f.file_field :attachment %>
      <%= f.submit "Save", class: "btn btn-primary" %>
   <% end %>
</div>

이제 서버를 시작하고 http : // localhost : 3000을 방문하십시오. 다음과 같은 화면이 생성됩니다.

마지막으로해야 할 일은 허용 된 파일 유형 목록을 필터링하는 것입니다. 이를 위해 app / uploaders / attachment_uploader.rb에 아래와 같이 간단한 코드를 추가해야합니다.

class AttachmentUploader < CarrierWave::Uploader::Base
   storage :file
   
   def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
   end
   
   def extension_white_list
      %w(pdf doc htm html docx)
   end
end

이제 서버를 시작하고 http : // localhost : 3000을 방문하십시오. 이제 잘못된 형식을 입력하십시오. 아래와 같이 잘못된 메시지가 생성됩니다.

에 대한 자세한 내용은 File 개체, 당신은 통과해야 Ruby Reference Manual.