【问题标题】:How to make sure images uploaded with paperclip have unique names?如何确保使用回形针上传的图像具有唯一的名称?
【发布时间】:2015-07-04 13:08:46
【问题描述】:

我正在使用回形针保存图像。我创建了一个图像模型以将它们保存给我的公共主管

class Image < ActiveRecord::Base
  has_attached_file :file,
                    :url => "assets/projects_description_images/:style/:basename.:extension",
                    :path => ":rails_root/public/assets/projects_description_images/:style/:basename.:extension"


  validates_attachment :file,
                       :presence => true,
                       content_type: {content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"]},
                       :size => {:in => 0..50.megabytes}
end

但是,如果我添加了一个名为“main.jpg”的图像,然后在显示第一个创建的图像时创建另一个名称为“main.jpg”的图像,它会显示第二个图像。我无法知道将使用的确切名称,但我可以肯定会有重复。如果我可以将文件名保存为类似的东西,那就太好了

main_(unique_string).jpg

任何线索如何做到这一点?

【问题讨论】:

  • 好吧,您可以使用时间到 ms 或 ns 级别,将其呈现为字符串,这样 main_{timestring}.jpg 就可以保证是唯一的。只要您存储了名称,您就可以始终找到它,但永远不要复制它。如果我记得很容易使用 Time 类。

标签: ruby-on-rails ruby-on-rails-4 file-upload paperclip uniqueidentifier


【解决方案1】:

Andrey Turkin (trevorturk.com/2009/03/22/randomize-filename-in-paperclip) 提供的答案解决了我的问题。需要注意的一件事是,使用 rails 4.2 我必须更改 ActiveSupport::SecureRandom.hex(16) 只是

SecureRandom.hex(16)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2011-05-06
    相关资源
    最近更新 更多