Ruby on Rails - 檔案上傳



您可能需要一個功能,讓網站訪問者能夠將檔案上傳到您的伺服器。Rails 使得處理此需求非常容易。現在我們將繼續進行一個簡單的小型 Rails 專案。

像往常一樣,讓我們從一個名為 testfile 的新 Rails 應用程式開始。讓我們使用簡單的 rails 命令建立應用程式的基本結構。

tp> rails new testfile

在開始應用程式開發之前,我們應該安裝如下所示的 gem 檔案:

gem install carrierwave
gem install bootstrap-sass

開啟您的 Gemfile,並在底部新增以下兩個 gem,如下圖所示:

GEM

在 gem 檔案中新增 gem 後,我們需要在控制檯中執行以下命令:

bundle install

建立模型

我們需要建立一個模型,其中包含兩個字串:name 和 attachment,如下所示:

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

現在開啟 resume 模型並呼叫上傳器,如下所示。Resume 模型位於 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 檔案中新增 bootstrap 實現。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 !@resume.errors.empty? %>
   <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>

現在啟動伺服器並訪問 https://:3000。它將生成類似於以下螢幕的螢幕:

Output

我們需要做的最後一件事是過濾允許的檔案型別列表。為此,我們需要在 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

現在啟動伺服器並訪問 https://:3000。現在輸入錯誤的格式;它將生成錯誤訊息,如下所示:

Output Wrong

有關 File 物件的完整詳細資訊,您需要查閱 Ruby 參考手冊

廣告
© . All rights reserved.