Ruby-on-rails rails - 回形针文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4306746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails - Paperclip file name
提问by AnApprentice
using rails with Paperclip, I can use the following to get the filename during a before_create:
将 rails 与 Paperclip 一起使用,我可以使用以下内容在 before_create 期间获取文件名:
extension = File.extname(photo_file_name).downcase
扩展名 = File.extname(photo_file_name).downcase
How do I get JUST the file name.. Right now I have photo_file_name which provides the entire file, titlename.pdf
我如何获得文件名..现在我有 photo_file_name 提供整个文件,titlename.pdf
i need just titlename without the .pdf
我只需要没有 .pdf 的 titlename
Thanks
谢谢
Updating with code:
用代码更新:
photo.rb:
照片.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
回答by Jacob Relkin
Use File.basenamewith the optional suffixargument like this:
File.basename与可选suffix参数一起使用,如下所示:
file_name = File.basename(photo_file_name, File.extname(photo_file_name));
Works on my machine:
在我的机器上工作:


回答by user3056122
Paperclip attachment has the 'original_filename' method for this.
回形针附件为此具有 'original_filename' 方法。
回答by rusllonrails
user.logo.original_filename
=> 'test.jpg'
回答by Adriano Resende
Another option is set to default, work for all upload.
另一个选项设置为默认值,适用于所有上传。
This example change name file to 'name default' for web, example: test áé.jpgto test_ae_www.foo.com.jpg
这个例子改名文件的名字默认“的网页,例如:test áé.jpg以test_ae_www.foo.com.jpg
helper/application_helper.rb
助手/application_helper.rb
def sanitize_filename(filename)
fn = filename.split /(?<=.)\.(?=[^.])(?!.*\.[^.])/m
fn[0] = fn[0].parameterize
return fn.join '.'
end
Create config/initializers/paperclip_defaults.rb
创建config/initializers/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
Need restart, after put this code
需要重新启动,放入此代码后
I hope it help! ;)
我希望它有帮助!;)

