在浏览器中使用 Javascript 预缓存文件?
我该怎么做:
- 页面加载
- javascript 将远程 PDF 文件加载到本地内存中
- 用户单击按钮/链接
- 系统启动 PDF 阅读器或启动下载对话框,其中 PDF 文件已在内存中
换句话说,这是常规的文件在浏览器中下载,除非文件已经在后台加载,以便在用户决定下载文件时加快其接收速度。
How can I do this:
- the page loads
- javascript loads a remote PDF file into local memory
- the user clicks a button/link
- the system launches the PDF reader or starts a download dialog with the PDF file already in memory
In other words, it's a regular file download in the browser EXCEPT that the file has already been loading in the background in order to speed up its receipt when/if the user decides to download the file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须对文件进行编码(可能通过 servlet),然后您可以通过 XHR 获取它,并将其写入数据 uri,然后您可以将其附加到按钮或链接。
这种技术可能只适用于小文件和最新的浏览器。
StackOverflow 不允许我将示例链接作为链接发布,因此要测试这个概念,您必须将以下行复制到 html 文件中,看看是否可以加载该链接:
当我测试时,这在 Chrome 中运行得很好刚才它已经在 Firefox 中部分工作了。它在我的 IE 版本中根本不起作用。
另一个潜在的解决方案是绝对确保 pdf 已被缓存,然后尝试将其加载到隐藏的 iframe 中。这是否有效将取决于用户如何设置浏览器。
考虑到困难,您应该考虑根本不这样做。
You would have to encode the file (perhaps via a servlet), then you could get it through an XHR, and write it into a data uri, which you could then attach to a button or link.
This technique would probably only work on small files and very recent browsers.
StackOverflow won't let me post an example link as a link, so to test the concept, you'll have to copy the following line into an html file and see if you can load the link:
This worked perfectly in Chrome when I tested it just now, and worked partially in Firefox. It didn't work at all in my version of IE.
Another potential solution is to make absolutely sure that the pdf is being cached, and then try to load it in a hidden iframe. Whether this works or not will depend on how the user has their browser set up.
You should consider not doing it at all, given the difficulties.