如何使用Paperclip为附件指定文件名?

时间:2010-11-09 02:14:43

标签: ruby-on-rails ruby paperclip attachment

我在服务器上有字节流,我想用Paperclip附加到模型类,我希望能够指定它们在文件系统中保存的名称。因为我有很多这些传入的文件,所以我更愿意将它们创建为Tempfiles,这样我就不必担心名称冲突并手动删除它们等等。这就是我正在做的事情:

desired_file_name = 'foo.txt'
Tempfile.open([File.basename(desired_file_name), File.extname(desired_file_name)]) do |tf|
  tf.write(content_stream)
  tf.rewind
  model_obj.paperclip_attachment = tf
end

这几乎可行。唯一的问题是,我的Paperclip附件最终得到一个临时文件名,如foo.txt.201029392u-gyh-foh96y.txt。那么如何告诉Paperclip将文件保存为什么?调用model_obj.paperclip_attachment_file_name = desired_file_name不起作用。 DB字段保存为该名称,但在文件系统上我仍然具有该临时文件名。

1 个答案:

答案 0 :(得分:7)

我认为你可以定义自己的插值interpolation来做到这一点。然后,您可以正常附加文件。例如:

# config/initializers/paperclip.rb
Paperclip.interpolates :custom_filename do |attachment, style|
  # Generate your desired file name here.
  # The values returned should be able to be regenerated in the future because
  # this will also be called to get the attachment path.

  # For example, you can use a digest of the file name and updated_at field.
  # File name and updated_at will remain the same as long as the file is not 
  # changed, so this is a safe choice.
  SHA1.sha1("#{attachment.original_filename}-#{attachment.updated_at}")
end

# app/models/post.rb
class Post < ActiveRecord::Base
  has_attached_file :attachment,
    :path => ':rails_root/public/system/:class/:attachment/:id/:style/:custom_filename',
    :url => '/system/:class/:attachment/:id/:style/:custom_filename'
end

请注意,这只会更改文件系统中的文件名。 model.attachment_file_namemodel.attachment.original_filename仍会保留原始文件名。