gpt4 book ai didi

ruby-on-rails-3 - 如何创建一个 Rails 应用程序,通过独特的自动生成的链接访问文件?

转载 作者:行者123 更新时间:2023-12-04 14:03:03 25 4
gpt4 key购买 nike

我有一个文件,我想让它在线下载,但只提供给选定的用户。

这是我想到的典型场景

A person who wants the file would typically go to the website and fill out a form to request access to the file.

If I would like to share the file with him/her, I would authorize the user which should generate a unique link that would be sent to the user via email. The link would be valid only for certain time period.



我会为此使用导轨。我正在寻找答案的事情:
  • 生成唯一下载链接的正确方法是什么?
  • 当用户在有效时间范围内单击链接时,如何开始下载文件?
  • 最佳答案

    首先,您需要设置一个用于存储 token 的模型:

    rails g model DownloadToken token:string expires_at:timestamp

    download_token.rb
    class DownloadToken < ActiveRecord::Base  

    attr_accessible :token, :expires_at
    before_create :generate_token

    def generate_token
    self.token = SecureRandom.base64(15).tr('+/=lIO0', 'abc123')
    end

    end

    接下来,设置 Controller 来处理提交的表单(或更改现有操作)并生成 token 、发送电子邮件等。
    class FooController < ApplicationController

    def create
    #process submitted form
    ...
    #create a token that expires in 24 hours
    @token = DownloadToken.create(:expires_at => Time.now + 24.hours)
    #send email and redirect..
    end
    end

    您需要确保您的邮件程序 View 包含以下内容:
    <%= link_to "Click Me", "/files/downloads?token=#{@token.token}" %>

    您还需要设置一个负责提供下载的 Controller ,它应该如下所示:
    class FileController < ApplicationController
    before_filter :check_token

    def check_token
    redirect_to :back, :flash => {:error => "Bad link"} if DownloadToken.where("token = ? and expires_at > ?", params[:token], Time.now).nil?
    end

    def download
    send_file '/home/your_app/downloads/yourfile.zip', :type=>"application/zip", :x_sendfile=>true
    end

    end

    路线.rb (假设 Foo 已经设置为 RESTful 资源)
    match 'files/download' => 'files#download'

    此代码未经测试,但它应该涵盖您需要的大部分内容,并让您了解要采取的方向。

    补充阅读:
  • SecureRandom
  • x_sendfile
  • ActionMailer basics
  • 关于ruby-on-rails-3 - 如何创建一个 Rails 应用程序,通过独特的自动生成的链接访问文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866521/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com