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

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

问题描述

对于rails项目,我需要向用户提供可下载的HTML版本的统计信息页面。我到目前为止,创建一个控制器操作,将设置标题如下,然后渲染并返回我的香草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,这是所需的。但是,这只会给我一个空白的HTML,没有任何图像或CSS嵌入。

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?

请问,

Sebastian

Sebastian

推荐答案

这是一个可能工作的过程...

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文件放在目录根目录中,资源位于资产 subdir中。

  • 您需要修改HTML文件中的所有资产项目URI,以指向资产目录中的项目,而不是其通常的位置。例如:

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

使用 ruby​​zip 宝石。

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天全站免登陆