一:建立表(用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>
代碼運行效果如下: