ruby-on-rails - 如何使用 Paperclip 为我的附件指定文件名?

标签 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 字段被保存为那个名称,但在文件系统上我仍然有那个临时文件名。

最佳答案

我想你可以定义自己的插值 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 仍将保留原始文件名。

关于ruby-on-rails - 如何使用 Paperclip 为我的附件指定文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4129921/

相关文章:

ruby-on-rails - PG::错误:SELECT DISTINCT,ORDER BY 表达式必须出现在选择列表中

Ruby on Rails 中的 JavaScript 集成测试

ruby-on-rails - ArgumentError : Unknown key: :order.有效键是: :class_name, :anonymous_class in Rails 4. 2.6

ruby-on-rails - Rails - Presenter 中的 Helper Singleton 和 Rails Route Helpers

ruby - ruby 中最短的 hex2bin?

ruby - 在带有 Ruby 的 Selenium Webdriver 中使用 css 选择器

ruby-on-rails - Prawn 不会画横线

ruby-on-rails - 使用 Rails Paperclip gem 在保存前预处理文件

ruby-on-rails - 验证Paperclip中的扩展-Ruby on Rails

ruby open-uri打开方法丢失文件扩展名打开图片