Ruby on Rails - 파일업로드, 다운로드 구현(carrierwave 사용)
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
명령어를 통해 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
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_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 %>
<%= 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
적용됬을까? 확인해보자.
넘나리 적용이 잘됬다. 끝!