rails + carrierwave S3:强制link_to下载

anu*_*anu 5 ruby-on-rails carrierwave

题:

我想强制link_to下载从S3获取的图像和pdf,而不是在浏览器窗口中打开它们.

link_to File.basename(asset.attachment.path), asset.attachment_url.to_s
Run Code Online (Sandbox Code Playgroud)

我寻找解决方案,但我发现的唯一解决方案是使用send_file或send_data在控制器中处理它,但这些对我来说不起作用.最后,我偶然发现了Carrierwave资源中的解决方案.

anu*_*anu 7

解:

这是非常有效的.使用'response-content-disposition'作为url的参数

link_to File.basename(asset.attachment.path), asset.attachment_url(:query => {"response-content-disposition" => "attachment"}).to_s
Run Code Online (Sandbox Code Playgroud)

在这里找到更多选项:https://github.com/carrierwaveuploader/carrierwave/blob/5aec4725a94fca2c161e347f02b930844d6be303/lib/carrierwave/uploader/versions.rb(第185行)


Chr*_*van 7

您可以通过添加fog_attributes方法对特定上载器的所有文件进行默认设置.

例如

# your_uploader.rb
def fog_attributes
  {'Content-Disposition' => "attachment"}
end
Run Code Online (Sandbox Code Playgroud)

这适用于未签名的请求!