加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – 如何创建一个rails应用程序,通过独特的自动

发布时间:2020-12-16 23:19:09 所属栏目:百科 来源:网络整理
导读:我有一个文件,我想提供在线下载,但仅限于选定的用户. 这是我想到的典型场景 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
我有一个文件,我想提供在线下载,但仅限于选定的用户.

这是我想到的典型场景

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.

我会使用rails来做这件事.我正在寻找的答案:

>生成下载的唯一链接的正确方法是什么?
>当用户在有效时间范围内点击链接时,如何开始下载文件?

解决方法

首先,您需要设置一个用于存储令牌的模型:
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

接下来,设置控制器来处理提交的表单(或更改现有操作)并生成令牌,发送电子邮件等.

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

您需要确保邮件程序视图包含以下内容:

<%= link_to "Click Me","/files/downloads?token=#{@token.token}" %>

您还需要设置一个负责提供下载的控制器,它应该如下所示:

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

routes.rb(假设Foo已经设置为RESTful资源)

match 'files/download' => 'files#download'

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

补充阅读:

> SecureRandom
> x_sendfile
> ActionMailer basics

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读