Ruby 多檔案上傳並寫入資料庫

來源:互聯網
上載者:User
一:建立表(用Ruby的 script/generate model attach) 順便把模型也產生
開啟 db/migrage/007_create_attaches.rb 修改成
class CreateAttaches < ActiveRecord::Migration
def self.up
    create_table :attaches, :force => true do |t|
      t.column :name,        :string # 附件名稱
      t.column :url,         :string # 資源路徑
      t.column :types,       :string # 附件類型,存副檔名
      t.column :size,        :integer # 附件大小
      t.column :last_update, :integer # 更新時間
    end
end

def self.down
    drop_table :attaches
end
end

執行 rake db:migrate 會自動建立表到指定的資料庫

二:建立立一個UploadController 其內容如下(只是測試用,沒有去美化)
class UploadController < ApplicationController

def index
    @attach_pages, @attaches = paginate :attaches, :order => 'last_update DESC', :per_page => 10
end

def add
    begin
      # 因為是多檔案上傳,所以這裡要迴圈
      params[:uploadFile].each do | file |
        if file.kind_of?(StringIO) || File.exist?(file)
    # 調用自訂的模型來上傳檔案,傳入session_id 來重新命名檔案,保證檔案不重名
    attach = Attach.new(file, session.session_id)
    attach.save
    end
      end
    rescue
      raise
    end
    redirect_to :action => "index"
end

end

三:修改剛才自動產生的模型 Attach
class Attach < ActiveRecord::Base

def initialize(upload, session_id)
    file_upload(upload, session_id) # 執行檔案上傳
    super()
    self.name = @name
    self.url   = @url
    self.types = @type
    self.size = @size
    self.last_update = @last_update
end

# 檔案上傳
def file_upload(upload, session_id)
    time_now = Time.now
    @init_dir = "upload/#{time_now.strftime('%Y-%m-%d')}"

    begin
      FileUtils.mkpath(upload_path) unless File.directory?(upload_path)
      if upload.kind_of?(StringIO)
        upload.rewind
      end
   
      origName = upload.original_filename
      baseName = File.basename(origName, ".*")    # 取得檔案名稱字
      extName = File.extname(origName).downcase # 取得副檔名
      tmpName = "_1"
      tmpExtName = "_" + time_now.to_i.to_s + extName
     
      # 重新命名
      baseName = session_id.nil? ? Digest::MD5.hexdigest(baseName).to_s : session_id.to_s
      baseName = baseName.upcase
      endName = baseName + tmpExtName
     
      # 產生不重複的檔案名稱
      while File.exist?(upload_path(endName))
        arr = endName.scan(/[a-zA-Z0-9_]+/)[0].split("_")
    endName = 2 == arr.size ? (baseName + tmpName + tmpExtName ) : (baseName + "_" + arr[1].succ.to_s + tmpExtName )
      end
     
      # 將檔案寫入磁碟
      File.open(upload_path(endName), "wb") { |f| f.write(upload.read) }

      @name = origName
      @url = "/#{@init_dir}/#{endName}"
      @type = (extName.delete ".")
      @size = upload.size
      @last_update = time_now.to_i

    rescue
      raise
    end

end

# 產生絕對路徑
def upload_path(file = nil)
    "#{RAILS_ROOT}/public/#{@init_dir}/#{file.nil? ? '' : file}"
end
end

四:修改views/upload/index.rhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>檔案上傳測試</title>
</head>

<body>

<!-- 用於顯示已經上傳的檔案 -->
<table border="1">
<tr>
<% for column in Attach.content_columns %>
    <th><%= column.human_name %></th>
<% end %>
</tr>

<% for attach in @attaches %>
<tr>
<% for column in Attach.content_columns %>
    <td><%=h attach.send(column.name) %></td>
<% end %>
</tr>
<% end %>
</table>

<!-- 用[]命名是為了Ruby得到的是一個檔案數組 -->
<h1>檔案上傳</h1>
<% form_tag({:action => :add}, {:multipart => true}) do -%>

檔案名稱1:<%= file_field_tag "uploadFile[]" -%> <br/><br/>
檔案名稱2:<%= file_field_tag "uploadFile[]" -%> <br/><br/>
檔案名稱3:<%= file_field_tag "uploadFile[]" -%> <br/><br/>
檔案名稱4:<%= file_field_tag "uploadFile[]" -%> <br/><br/>
檔案名稱5:<%= file_field_tag "uploadFile[]" -%> <br/><br/>

<%= submit_tag "檔案上傳", :disable_with => "檔案上傳中..." , :name => "btnSave", :id => "btnSave" %>

<% end %>
</body>
</html>

代碼運行效果如下:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.