views:

279

answers:

3

Hey guys,

for a rails project I need to provide the user with a downloadable HTML version of a statistics page. I got so far as creating a controller action that will set the header as follows and then render and return my vanilla html page:

headers["Content-Type"] ||= 'application/x-unknown'
headers["Content-Disposition"] = "attachment; filename=\"#{filename}\""

This will make the browser pop open the download dialog instead of rendering the html right away, which is desired. However, this only gives me the blank HTML without any images or css embedded.

What I'd like to do is essentially the same thing that the browser does when you click on the "Save Page as" menu item (probably even zip images, css and html file up in a zip file and return that).

What's the right way to do this? Is there a way to invoke the browser "Save page as" dialog with a header setting?

Regards,

Sebastian

A: 

Could you try setting the HTTP content type to "application/octet-stream" and let me know if that helps?

Barry Gallagher
nope, that doesn't do anything different than 'application/x-unknown'
Sebastian
+1  A: 

Here is a procedure that might work...

  1. Assemble the things to be downloaded -- the rendered HTML, images, CSS, etc. -- into a staging dir on the filesystem.

    • Give the dir a definitely unique name (use timestamp maybe).
    • You could put the rendered HTML file in the dir root, and the assets in an assets subdir.
    • You'll need to modify all the asset item URIs in the HTML file to point to the item in the assets dir instead of its usual location. For example:

      <img src='assets/my_img.jpg'>.

  2. Zip it up into a *.zip archive using the rubyzip gem.

  3. Use Rails's send_file method to open up a download dialog.

    send_file '/path/to.zip'

  4. Delete the staging dir and zip archive. Avoid deleting it while user is downloading. Perhaps set up a cron job to clean up once a day.

Ethan
That's exactly what I ended up doing in the meantime :-) Thanks a lot anyway!!!
Sebastian
A: 

Worked for me:

send_data(render, :filename => "filename.ext")
Daniel Dengler