允许用户从S3存储中下载文件

Rub*_*bie 15 amazon-s3 paperclip ruby-on-rails-3

现在我正在使用Amazon S3和Paperclip,它允许我的用户上传与他们正在创建的事件相关联的图像.我的最终目标是,因为其他人可以查看此事件,以便能够点击图像并让它提示保存到他们的计算机.截至目前,单击该链接将在浏览器窗口中打开图像.我宁愿让它要求他们下载.所有图像仅保存在S3上,而不是本地.如果可能,也需要隐藏暴露的s3网址或伪装它

这是我目前的设置

的index.html

<%= link_to 'Download Creative', event.creative.url, class: "btn btn-info" %>
Run Code Online (Sandbox Code Playgroud)

Event.rb

has_attached_file :creative,
                :styles => { :thumb => "150x150", :custcreative => "250x75" },
                :path => ":attachment/:id/:style.:extension",
                :s3_domain_url => "******.s3.amazonaws.com",
                :storage => :s3,
                :s3_credentials => Rails.root.join("config/s3.yml"),
                :bucket => '*****',
                :s3_permissions => :public_read,
                :s3_protocol => "http",
                :convert_options => { :all => "-auto-orient" },
                :encode => 'utf8'
Run Code Online (Sandbox Code Playgroud)

希望有人可以帮助我.

gui*_*eva 28

为了避免额外加载你的应用程序(在Heroku中保存dyno的时间),我宁愿做这样的事情:使用附件将此方法添加到模型中:

def download_url(style_name=:original)
  creative.s3_bucket.objects[creative.s3_object(style_name).key].url_for(:read,
      :secure => true,
      :expires => 24*3600,  # 24 hours
      :response_content_disposition => "attachment; filename='#{creative_file_name}'").to_s
end
Run Code Online (Sandbox Code Playgroud)

然后在你的视图/控制器中使用它,如下所示:

<%= link_to 'Download Creative', event.download_url, class: "btn btn-info" %>
Run Code Online (Sandbox Code Playgroud)


san*_*xus 16

为了使这项工作,我刚刚在控制器中添加了一个新动作,所以在你的情况下它可能是:

#routes
resources :events do
  member { get :download }
end

#index
<%= link_to 'Download Creative', download_event_path(event), class: "btn btn-info" %>

#events_controller
def download
  data = open(event.creative_url)
  send_data data.read, :type => data.content_type, :x_sendfile => true
end
Run Code Online (Sandbox Code Playgroud)

编辑:下载控制器动作的正确解决方案可以在这里找到(我已经更新了上面的代码):强制链接下载MP3而不是播放它?