它不記錄(而沒有太大的意義),但它看起來像the options UploadedFile#initialize
takes是:tempfile
,:filename
,:type
和:head
:
def initialize(hash) # :nodoc:
@tempfile = hash[:tempfile]
raise(ArgumentError, ':tempfile is required') unless @tempfile
@original_filename = encode_filename(hash[:filename])
@content_type = hash[:type]
@headers = hash[:head]
end
你調用改變這個應該工作:
ActionDispatch::Http::UploadedFile.new tempfile: 'tempfilefoo',
filename: 'filename_foo.jpg', type: 'content_type_foo', head: 'headers_foo'
或者您可以在初始化後設置它們:
file = ActionDispatch::Http::UploadedFile.new tempfile: 'tempfilefoo', filename: 'filename_foo.jpg'
file.content_type = 'content_type_foo'
file.headers = 'headers_foo'
我不知道我理解你的第二個問題,「而且我怎麼能從文件中讀取實例這些屬性?」
您可以提取任何路徑的文件名(或最後一個組件)與File.basename
:
file = File.new('path/to/file.png')
File.basename(file.path) # => "file.png"
如果你想獲得對應於文件擴展名的內容類型,你可以使用Rails的啞劇模塊:
type = Mime["png"] # => #<Mime::Type:... @synonyms=[], @symbol=:png, @string="text/png">
type.to_s # => "text/png"
您可以File.extname
把這個在一起,它給你的擴展:
ext = File.extname("path/to/file.png") # => ".png"
ext = ext.sub(/^\./, '') # => "png" (drop the leading dot)
Mime[ext].to_s # => "text/png"
您可以通過鍵入Rails的控制檯Mime::SET
,或looking at the source,這也說明了如何在情況下注冊其他MIME類型,你希望其他類型的文件看到所有的MIME類型的Rails知道的列表。
感謝喬丹,我應該如何從文件實例中獲取標題? – Starkers 2014-10-08 17:29:10
@Starkers文件實例沒有「標題」。一個文件實例只是一個指向你的(服務器)硬盤上文件的指針。標題特定於HTTP,File與HTTP無關。 – 2014-10-08 17:31:42