Rails - Paperclip文件名

19
使用Rails和Paperclip,我可以在before_create中使用以下代码获取文件名:
extension = 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
4个回答

26

使用可选的 suffix 参数和 File.basename 方法,像这样:

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

在我的电脑上可以工作:

alt text


4
Stackoverflow 让你等待 6 分钟。 - AnApprentice

23

在Paperclip附件中,有一个名为“original_filename”的方法用于此目的。


1
我不确定这是否符合原帖作者的要求。他们想要的是 a_file,而不是 a_file.pdf - matsjoyce
1
这个问题的标题似乎不够具体。人们可能会在这里搜索“paperclip文件名”,并找到这个正确的答案,所以即使它不是这个问题的提问者所问的,他们也会给它点赞。 - Jason Swett

11
user.logo.original_filename
  => 'test.jpg'

0

另一个选项是设置为默认值,适用于所有上传。

此示例将文件名更改为“名称默认”用于 Web,例如:test áé.jpg 更改为 test_ae_www.foo.com.jpg

helper/application_helper.rb

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

创建 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

在放置此代码后需要重新启动

希望它有所帮助!;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接