2010-11-29 161 views
14

使用導軌與回形針,我可以使用下面的一個before_create期間獲得的文件名:軌道 - 回形針文件名

延長= File.extname(photo_file_name).downcase

如何得到公正的文件名..現在我有photo_file_name提供整個文件,titlename.pdf

我只需要TITLENAME沒有.PDF

感謝

更新與代碼:

photo.rb:

before_create :obfuscate_file_name 

    #Paperclip for photo 
    has_attached_file :photo, 
...... 


private 

    def obfuscate_file_name 
    extension = File.extname(photo_file_name).downcase 
    fileNameOnly = File.basename(photo_file_name).downcase 
    self.photo.instance_write(:file_name, "#{fileNameOnly}_#{ActiveSupport::SecureRandom.hex(32)}#{extension}") 
    end 

回答

22

使用File.basename使用可選suffix說法是這樣的:

file_name = File.basename(photo_file_name, File.extname(photo_file_name)); 

作品在我的機器上:

alt text

+0

試過了,它不起作用..我會用上面的代碼更新。 – AnApprentice 2010-11-29 18:25:53

+0

這樣做。感謝Jacob。 – AnApprentice 2010-11-29 18:29:37

18

回形針附件具有「original_filename」方法。

0

另一個選項設置爲默認值,適用於所有上傳。

這個例子改名文件的名字默認「的網頁,例如:test áé.jpgtest_ae_www.foo.com.jpg

幫手/ application_helper.rb

def sanitize_filename(filename) 
    fn = filename.split /(?<=.)\.(?=[^.])(?!.*\.[^.])/m 
    fn[0] = fn[0].parameterize 
    return fn.join '.' 
end 

創建配置/初始化/ paperclip_defaults.rb

include ApplicationHelper 

Paperclip::Attachment.default_options.update({ 
    :path => ":rails_root/public/system/:class/:attachment/:id/:style/:parameterize_file_name", 
    :url => "/system/:class/:attachment/:id/:style/:parameterize_file_name", 
}) 

Paperclip.interpolates :parameterize_file_name do |attachment, style| 
    "#{sanitize_filename(attachment.original_filename)}_www.foo.com" 
end 

需要r estart,把這個代碼後

我希望它有幫助! ;)