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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – 如何创建一个rails应用程序,通过独特的自动生成链接使文件可访问?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个文件,我想提供在线下载,但仅限于选定的用户.

这是我想到的典型场景

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

原文链接:https://www.f2er.com/ruby/264798.html

猜你在找的Ruby相关文章