rails:模拟“将页面另存为"行为 [英] rails: emulate "Save page as" behaviour

查看:15
本文介绍了rails:模拟“将页面另存为"行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 rails 项目,我需要为用户提供可下载的 HTML 版本的统计页面.我已经创建了一个控制器操作,它将按如下方式设置标题,然后呈现并返回我的 vanilla html 页面:

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}"" 

这将使浏览器弹出下载对话框,而不是立即呈现 html,这是我们想要的.但是,这只会给我没有嵌入任何图像或 css 的空白 HTML.

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.

我想做的事情本质上与当您单击页面另存为"菜单项时浏览器所做的事情相同(甚至可能将 zip 图像、css 和 html 文件放在一个 zip 文件中并返回).

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?

问候,

塞巴斯蒂安

推荐答案

这是一个可能有效的程序...

Here is a procedure that might work...

  1. 将要下载的内容(呈现的 HTML、图像、CSS 等)组装到文件系统上的暂存目录中.

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

  • 为目录指定一个绝对唯一的名称(可能使用时间戳).
  • 您可以将渲染的 HTML 文件放在目录根目录中,并将资产放在 assets 子目录中.
  • 您需要修改 HTML 文件中的所有资产项目 URI,以指向 assets 目录中的项目,而不是其通常的位置.例如:

  • 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:

.

使用 rubyzip 宝石.

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

使用 Rails 的 send_file 方法来打开一个下载对话框.

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

send_file '/path/to.zip'

删除暂存目录和 zip 存档.避免在用户下载时删除它.也许设置一个 cron 作业每天清理一次.

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.

这篇关于rails:模拟“将页面另存为"行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆