rails: emulate “Save page as” behaviour

2019-01-20 19:51发布

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

3条回答
我只想做你的唯一
2楼-- · 2019-01-20 20:03

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.

查看更多
\"骚年 ilove
3楼-- · 2019-01-20 20:15

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

查看更多
狗以群分
4楼-- · 2019-01-20 20:20

Worked for me:

send_data(render, :filename => "filename.ext")
查看更多
登录 后发表回答