Last Updated: February 25, 2016
·
1.103K
· alexisraca

Carrierwave-Rails start a download without iframe/javascript hacks

There's a problem some times involving download files on browsers, mostly when trying to use javascript like Backbone.js, Angular.js or any other sub js framework integrated to your rails application, this can be some times hacky or complicated, but rails has a realy easy way to handle downloads without even adding a javascript hack when you have a one page application.

just add the url to the link:

<a href='<%= item_path(@item) %>'> </a>

and in your controller use the magical method:

send_file(
  @item.field.url,
  filename: "#{@item.name}.#{@item.extension}",
  disposition: "attachment"
  )

explanation:

if you look at the rails API http://apidock.com/rails/ActionController/Streaming/send_file

send file receives 2 arguments:

  • the path to the url
  • options

inside options it has many possibilities but to make this realy easy all you need is:

  • filename: with this option you need to pass "filename.extension" like "image.jpg" this way the browser will handle the name file but also if it has a extension the method will automatically handle the request as "html/type" where type is the extension like "html/pdf" or "html/jpg" and automatically start a download

  • disposition: for this parameter you need to set as "attachment" because some files like images are handled "inline" inside the browser and delivered in a new window or loading an empty window with the image

there are other possible arguments but are for combinations when handling specific chances like when not having an extension in the file to be auto handled with filename option.

hope it was helpful