Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails + carrierwave S3: force link_to to download

Question:

I would like to force link_to to download images and pdfs fetched from S3 instead of opening them in the browser window.

link_to File.basename(asset.attachment.path), asset.attachment_url.to_s

I looked for solutions but the only ones I found are to handle it in the controller using send_file or send_data but these did not work for me. Finally I stumbled upon the solution in Carrierwave sources.

like image 262
anu Avatar asked Jul 13 '13 15:07

anu


2 Answers

Solution:

This is what works super well. Use 'response-content-disposition' as a parameter to url

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

Find more options here: https://github.com/carrierwaveuploader/carrierwave/blob/5aec4725a94fca2c161e347f02b930844d6be303/lib/carrierwave/uploader/versions.rb (line 185)

like image 96
anu Avatar answered Nov 17 '22 22:11

anu


You can default this for all files of a particular uploader by adding a fog_attributes method.

e.g.

# your_uploader.rb
def fog_attributes
  {'Content-Disposition' => "attachment"}
end

This works with requests that aren't signed as well!

like image 21
Chris O'Sullivan Avatar answered Nov 17 '22 23:11

Chris O'Sullivan