在保存图像之前,我使用这种方法来重命名图像:
def rename_avatar
self.avatar.instance_write :file_name, Time.now.to_i.to_s
end
before_post_process :rename_avatar
该图像被重命名为当前时间,但没有添加文件类型,因此只保存1334487964.而不是1334487964.jpg。
我错过了什么?我认为:file_name只包含文件名,不包括文件类型。
在保存图像之前,我使用这种方法来重命名图像:
def rename_avatar
self.avatar.instance_write :file_name, Time.now.to_i.to_s
end
before_post_process :rename_avatar
该图像被重命名为当前时间,但没有添加文件类型,因此只保存1334487964.而不是1334487964.jpg。
我错过了什么?我认为:file_name只包含文件名,不包括文件类型。
这是我解决问题的方式:
def rename_avatar
#avatar_file_name - important is the first word - avatar - depends on your column in DB table
extension = File.extname(avatar_file_name).downcase
self.avatar.instance_write :file_name, "#{Time.now.to_i.to_s}#{extension}"
end
由于 Paperclip
推荐使用 interpolates
,因此这个链接可以帮助你找到最佳方法。
https://wyeworks.com/blog/2009/7/13/paperclip-file-rename
我尝试了之前所有的解决方案,但它们对我来说并不起作用......然而,我创建了这个解决方案,它在所有样式上都能正常工作。
attr_accessor :avatar_update_file_name
has_attached_file :avatar,
:styles => {
:medium => "288x288#",
:small => "150x150#",
:thumb => "48x48#"
},
:path => YOUR_PATH + ":style/:basename.:extension",
:url => YOUR_PATH + ":style/:filename",
preserve_files: true
process_in_background :avatar, only_process: [:medium, :small, :thumb, :original]
after_save :rename_avatars
def rename_avatars
if self.avatar_update_file_name == true
new_file_hash = "#{SecureRandom.urlsafe_base64}"
new_file_name = ""
(self.avatar.styles.keys+[:original]).each do |style|
path = avatar.path(style)
if(File.file?(path))
File.chmod(0777, File.dirname(path))
new_file_name = "#{new_file_hash}.#{extension}"
FileUtils.move(path, File.join(File.dirname(path), new_file_name))
end
end
self.avatar_update_file_name = false
self.avatar_file_name = new_file_name
self.save!
end
end
avatar_update_file_name = true
时,这将在您的样式上循环,并且每个对象调用一次仅更新记录。avatar = new Avatars
#... upload and work with files
avatar.avatar_update_file_name = true
avatar.save!