gpt4 book ai didi

javascript - 当文件开始下载时触发​​ javascript 事件 - 当收到响应时

转载 作者:行者123 更新时间:2023-11-28 01:55:39 25 4
gpt4 key购买 nike

目的是在服务器准备下载文件时显示一个等待微调器图标。在我的用例中,我正在生成一个大型报告,这在服务器端需要一些时间才能调用浏览器的下载/另存为提示。我可以毫无问题地显示等待微调器,但找不到清除它的方法。

当前相关代码:

<h:commandButton id="generate" value="Generate Report" type="submit" 
action="#{bean.generateReport()}"
onclick="#{rich:component('waitIcon')}.start();"/>

<a4j:status id="waitIcon">
<f:facet name="start">
<h:graphicImage value="/images/ai.gif" alt="ai" />
</f:facet>
</a4j:status>

其中 bean.generateReport() 是服务器端需要 1-10 秒的操作,然后返回下载响应。

这是使用 richfaces a4j:status 指示器,因为它提供了有用的 API,如 .start() 和 .stop() 但它也可以是任何 dom 元素并设置可见性。问题是我无法挂接正确的事件。我需要捕获类似 onresponsereceived 的内容...

我尝试过的解决方案:

使用 a4j:commandButton 提供了一个 oncomplete 事件,但是该按钮会生成一个 AJAX 请求,该请求无法开始下载。 (参见 h:command button oncomplete action)

使用 window.timeout 函数调用组件上的 .stop()。这在功能层面上有效,但由于生成时间在 1-10 秒之间大幅波动,这使得指标有点不反射(reflect)现实。

有人对处理这个有什么好的想法吗?

最佳答案

一种方法是返回到同一页面,在该页面中您有条件地呈现一段 JS 代码以启动实际下载。

<h:form>
...
<h:commandButton value="submit" action="#{bean.prepareFileForDownload}" />
<h:outputScript rendered="#{bean.fileReadyForDownload}">
// Do here your thing to indicate start of download.
window.location = '#{bean.fileDownloadURL}';
</h:outputScript>
</h:form>

另一种方法是每隔一段时间检查 cookie。您只需要生成一个 URL 安全值作为某种下载 token (System.currentTimeMillis() 非常适用于此)。

<h:form>
...
<input type="hidden" name="token" value="#{bean.token}" />
<h:commandButton value="submit" action="#{bean.downloadFile}" onclick="checkToken(this.form.token)" />
<h:outputScript>
function checkToken(token) {
var pollDownloadStart = setInterval(function() {
if (document.cookie.indexOf("download=" + token) > -1) {
document.cookie = "download=" + token + "; expires=" + new Date(0).toGMTString() + "; path=/";
clearInterval(pollDownloadStart);
// Do here your thing to indicate start of download.
}
}, 500);
}
</h:outputScript>
</h:form>

downloadFile() 中使用这个

// Prepare download here.
// ...

// Once finished, set cookie and stream download to response.
Cookie cookie = new Cookie("download", token);
cookie.setPath("/");
response.addCookie(cookie);
// ...

关于javascript - 当文件开始下载时触发​​ javascript 事件 - 当收到响应时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17115144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com