我有一个 PDF 文件,我不想通过我网站上的 URL 公开访问它。作为(轻微的)安全层,我想通过电子邮件向用户发送一个随机生成的唯一 URL,他们可以从中下载 PDF,我会将其存储在 AWS 或类似的东西上。
我觉得我被困在 routes.rb jail 里了,我不知道如何动态生成 URL,也不知道如何正确地创建随机 URL、跟踪它们或将它们链接到存储在本地或上的文件AWS。
有人对解决这个问题有什么建议吗?
最佳答案
您如何存储 PDF?如果你使用类似 Paperclip 的东西,您可以很容易地生成私有(private)文件的临时公共(public) URL:
class Attachment < ActiveRecord::Base
has_attached_file :file
# ...
def file_url
file.expiring_url(10)
end
end
file_url
将为该文件生成一个 10 秒有效的 URL。然后,在任何相关的 Controller 中,您都可以为文件本身提供一个“显示”方法,该方法在访问时快速重定向到私有(private) url:
class AttachmentsController < ApplicationController
# GET /whatever/attachments/:id
def show
redirect_to Attachment.find(params[:id]).file_url
end
end
要像您要发送的那样获得“随机”URL,您需要一个额外的步骤。您可以使用 SecureRandom.uuid
之类的东西生成一个长散列,并将其作为参数传递,并使用 AttachmentProxy
之类的简单模型。
类似于:
class AttachmentProxy < ActiveRecord::Base
has_one :attachment
# has an attribute called 'key', indexed...
end
在你的 Controller 中:
class AttachmentProxyController < ApplicationController
def show
proxy = AttachmentProxy.find_by_key(params[:key])
redirect_to proxy.attachment.file_url
end
end
关于ruby-on-rails - 如何随机生成文件链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19847292/