Re: [問題] 怎麼管理上傳的檔案呢?

看板Ruby作者 (Midnight Blue)時間17年前 (2006/12/07 00:06), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《isnora (nora)》之銘言: : 各位前輩大家好,小弟最近開始學習ROR設計程式 : 但是今天遇到一個上傳的問題,我不知道要怎麼把上傳的檔案傳到我想要的目錄 : 下,目前拿來學習的書是 Agile Web Development with Rails : 這本書有一個上傳的例子,但是它是將圖片存到資料庫裡,但是我並不想要這麼 : 做,不知道有沒有辦法知道上傳的位置… : 我使用的 WEB SERVER 是 Mongrel ,我找了目錄下的 tmp 也沒有這些檔案 : 救救我吧… 我想你遇到的問題應該是寫檔的問題。下面列舉一個簡單的例子。 def self.save(prefixPath, objFile) # objFile 的 data type 測試 if (!objFile.kind_of? StringIO) && (!objFile.kind_of? Tempfile) return false end # 檢查預儲存的路徑是否存在,若否,則建立之 Dir.mkdir(prefixPath) if !FileTest.directory?(prefixPath) if objFile.original_filename == '' return false else # 檢查在暫存目錄下是否有同檔名檔案 if FileTest.exist?(prefixPath + '/' + objFile.original_filename) # Policy 選擇:重新命名或覆蓋 end # 將檔案寫入 wrtFilePath = prefixPath + '/' + objFile.original_filename File.open(wrtFilePath, 'w') { |f| # 做一些對 file 的限制,如大小等 if objFile.size <= $MAX_FILE_SIZE f.write(objFile.read) else return false end } return true end end 實際上要發揮 RoR 的 Active Record 以及其 OO 的本能,則應該是搭配 super 來做 Method overriding,比方說: class Student < ActiveRecord::Base def save # 做一些檔案寫入,如圖片上傳 super # 做繼承於 super class 的 method save end def destroy # 做一些檔案的刪除 super # 做繼承於 super class 的 method destroy end ... end -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.119.164.78

12/07 07:08, , 1F
太感謝了…我會好好的試試~
12/07 07:08, 1F
文章代碼(AID): #15TkgBM9 (Ruby)
文章代碼(AID): #15TkgBM9 (Ruby)