代码之家  ›  专栏  ›  技术社区  ›  Jeff

如何使用回形针为附件指定文件名?

  •  1
  • Jeff  · 技术社区  · 15 年前

    我在服务器上有字节流,我想用回形针将它们附加到一个模型类上,并且我想能够指定它们在文件系统上保存为的名称。因为我有很多这些传入文件,所以我希望能够将它们创建为 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
    

    那很管用。唯一的问题是,我的回形针附件的临时文件名是foo.txt.201029392u-gyh-foh96y.txt。那么我如何告诉回形针我的文件保存为什么呢?打电话 model_obj.paperclip_attachment_file_name = desired_file_name 不起作用。DB字段保存为该名称,但在文件系统中,我仍然有该tempfile名称。

    1 回复  |  直到 15 年前
        1
  •  7
  •   htanata    14 年前

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

    推荐文章