Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

html - rails: emulate "Save page as" behaviour

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...