Back end/Ruby on rails

Ruby on Rails - 파일업로드, 다운로드 구현(carrierwave 사용)

Ideveloper2 2018. 2. 11. 04:00

Ruby on Rails - 파일업로드, 다운로드 구현



https://www.tutorialspoint.com/ruby-on-rails/rails-file-uploading.htm 참고하여 기능을 구현하였다.

앞서 진행하던 tinymce와 연결되어 이미 구현되어있는 프로젝트로 진행하는 점을 참고하기 바란다.



1. carrierwave gem 설치하기


gem "carrierwave" 를 gem file에 추가해주고,bundle install 해주기


or


gem install carreierwave 터미널에 치기



2.작성 되어있는 모델에 attachment 속성 추가해주기


class CreatePosts < ActiveRecord::Migration[5.1]
 def change
   create_table :posts do |t|
     t.text :content
     t.string :title
     t.string :attachment -> 속성을 추가해주었다.
     t.timestamps
   end
 end
end

기존 rails g model Post content:text titlet:string 명령어로 모델을 만들었었기에,

마이그레이션 파일에 가서 t.string :attachment를 추가해주었다.
3.업로더 만들기
rails g uploader attachment

명령어를 통해 carrierwave gem을 깔았으므로, 위 명령어를 실행한다.



4.모델 수정(post모델이 기존에있었으므로, post모델에 필자는 작성해주었음.)

class Post < ApplicationRecord
 mount_uploader :attachment, AttachmentUploader
 # Tells rails to use this uploader for this model.
 validates :title, presence: true
 # Make sure the title is present.
end

위 과정을 통해 이 모델은 uploader를 사용해준다고 명시해준다.
uninitialized constant Post::AttachmentUploader 라는 메시지가 간혹 뜨는데


config/application.rb 에 가서 


require 'carrierwave'

require 'carrierwave/orm/activerecord'


를 추가해주면 해결된다.


5. _form 수정하기

<%= form_with(model: post, local: true, multipart: true) do |form| %>
<% if post.errors.any? %>
   <div id="error_explanation">
     <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>

     <ul>
     <% post.errors.full_messages.each do |message| %>
      <li><%= message %></li>
     <% end %>
    </ul>
   </div>
 <% end %>

<div class="actions">
   <%= form.label :제목 %>
  <%= form.text_field :title%>
   <%= form.label :내용 %>
  <%= tinymce :language => "ko" %>
  <%= form.text_area :content, id: :post_content, class: "form-control tinymce", rows: "10" %>
   <%= form.file_field :attachment %>
  <%= form.submit %>
 </div>
<% end %>

_form.html 에 들어가 위와 같이 수정해준다. (필자는 scaffolding을 사용해서 form_with으로 _form.html 안에 새글을작성하는 form이 들어가 있음. 상황에 따라 새로운글을 작성하는 화면에 가서 고쳐주면 된다.)

   <%= 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 %>
form for라면 위와 같은 형태일 것이다.


6.download 링크 추가하기
 <%= link_to "Download file", @post.attachment_url, download: "Post_#{@post.id}_attachment" %>


위와 같은 코드를 포스팅한 글을 보는 뷰 파일에 넣어주면 된다.



다음과 같이 파일을 첨부할 수 있고,만약 파일을 첨부한다면



위와 같이 파일이 첨부되어 다운로드하는 링크가 나온것을 알수있다.
끄-읕
7.추가기능( 업로드 되는 파일 형식 제한하기)
이미지 파일만 업로드 하게 한다고 가정해보자.

  # Add a white list of extensions which are allowed to be uploaded.
 # For images you might use something like this:
 # def extension_whitelist
 #   %w(jpg jpeg gif png)
 # end

위와 같이 uploaders/attachment_uploader.rb에 주석처리 되어있는 부분을


 # Add a white list of extensions which are allowed to be uploaded.
 # For images you might use something like this:
 def extension_whitelist
   %w(jpg jpeg gif png)
 end

위와 같이 풀어주게 되면 타입 형식을 정할 수 있게된다.
적용됬을까? 확인해보자.

넘나리 적용이 잘됬다. 끝!