[英]How can I specify a file name for my attachment with Paperclip?
我想使用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
那幾乎可以工作。 唯一的問題是,我的回形針附件的最終臨時文件名為foo.txt.201029392u-gyh-foh96y.txt。 那么,如何告訴Paperclip將文件另存為? 調用model_obj.paperclip_attachment_file_name = desired_file_name
不起作用。 DB字段被保存為該名稱,但是在文件系統上,我仍然具有該tempfile名稱。
我認為您可以定義自己的插值插值法來做到這一點。 然后,您可以正常附加文件。 例如:
# 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
仍將保留原始文件名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.