有没有办法通过JavaScript检测下载的开始? [英] Is there a way to detect the start of a download in JavaScript?

查看:181
本文介绍了有没有办法通过JavaScript检测下载的开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们目前的项目中,我们提供的PDF下载可以由用户通过他提交的HTML表单进行定制。动态生成PDF需要几秒钟的时间,我想将其可视化,例如通过禁用提交按钮直到下载开始。不幸的是,我找不到一种方式来检测下载开始的时间*。所以我不知道什么时候重新启动提交按钮。

In our current project we are providing a PDF download that can be customized by the user through an HTML form he submits. It takes several seconds to dynamically generate the PDF and I'd like to visualize this, e.g. by disabling the submit button until the download starts. Unfortunately, I couldn't find a way to detect when the download starts*. So I wouldn't know when to re-enable the submit button.

我已经尝试指定一个IFrame作为我的HTML表单的目标,希望 onload 事件将被触发。然而,这并不是因为PDF以 Content-disposition:attachment 标题发送,并且实际上并未加载到IFrame中。

I already tried to specify an IFrame as the target of my HTML form, hoping that the onload event would be triggered. It is not, however -- probably because the PDF is sent with a "Content-disposition: attachment" header and it is not actually loaded into the IFrame.

我现在可以想到的唯一解决办法是将PDF生成到服务器上的一个临时文件,我想避免这种情况。

The only solution I can think of right now involves generating the PDF to a temporary file on the server, which I would like to avoid.

*)让我澄清一点:我不需要知道下载是否完成,即使它真的开始了。我想检测浏览器会询问用户是打开还是保存文件的点。我想这是在浏览器收到HTTP标头时发生的。

*)Let me clarify this: I wouldn't need to know if the download was finished or even if it was really started. I'd like to detect the point at which the browser will ask the user whether to open or to save the file. I guess this happens when the browser receives the HTTP header.

推荐答案

你想要的是能够检测何时下载的文件从0更改为正值。据我所知,这是不可能的,使用javascript - 您需要一个可以访问客户端文件系统的插件。

What you want is to be able to detect when the size of the downloaded file changes from 0 to a positive value. As far as I know it is impossible to do that with javascript - you need a plug-in that can access the client's file system.

推荐的工作:创建一个每次下载的会话让客户端轮询服务器有关下载的状态。这可能是不存在,不开始,开始,完成。您需要一些服务器端的工作来持久化和更新下载的状态以及AJAX框架。

A recommended work around: Create a session per download. Have the client poll the server about the status of the download. This could be "non existed", "not started", "started", "finished". You need some server's side work to persist and update the status of the download plus an AJAX framework.

这篇关于有没有办法通过JavaScript检测下载的开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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