2014-10-08 67 views
2

在軌控制檯:讀寫文件屬性

ActionDispatch::Http::UploadedFile.new tempfile: 'tempfilefoo', original_filename: 'filename_foo.jpg', content_type: 'content_type_foo', headers: 'headers_foo' 
=> #<ActionDispatch::Http::UploadedFile:0x0000000548f3a0 @tempfile="tempfilefoo", @original_filename=nil, @content_type=nil, @headers=nil> 

我可以寫一個字符串@tempfile,然而@original_filename@content_type@headers保持爲nil

這是爲什麼,我該怎麼寫信息到這些屬性?

我怎樣才能從文件實例這些屬性?

File.new('path/to/file.png') 

回答

2

它不記錄(而沒有太大的意義),但它看起來像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知道的列表。

+0

感謝喬丹,我應該如何從文件實例中獲取標題? – Starkers 2014-10-08 17:29:10

+0

@Starkers文件實例沒有「標題」。一個文件實例只是一個指向你的(服務器)硬盤上文件的指針。標題特定於HTTP,File與HTTP無關。 – 2014-10-08 17:31:42

1

以下應該可以幫助您:

upload = ActionDispatch::Http::UploadedFile.new({ 
    :tempfile => File.new("#{Rails.root}/relative_path/to/tempfilefoo") , #make sure this file exists 
    :filename => "filename_foo" # use this instead of original_filename 
}) 
upload.headers = "headers_foo" 
upload.content_type = "content_type_foo" 

我不明白的「我怎樣才能從文件中讀取實例這些屬性?」你到底想要什麼,去做。 或許,如果你想讀的臨時文件,可以使用:

upload.read # -> content of tempfile 
upload.rewind # -> rewinds the pointer back so that you can read it again. 

希望它能幫助:)讓我知道,如果我有誤解。