我有一个允许用户下载动态生成文件的页面。生成它需要很长时间,所以我想显示一个“等待”指示器。问题是,我不知道如何检测浏览器何时接收到文件,以便我可以隐藏指示器。

我请求一个隐藏的表单,它post到服务器,并以一个隐藏的iframe作为其结果的目标。这样我就不会用结果替换整个浏览器窗口。我监听iframe上的“load”事件,希望它在下载完成时触发。

我将文件返回一个“Content-Disposition: attachment”头,这将导致浏览器显示“Save”对话框。但是浏览器不会在iframe中触发“load”事件。

我尝试过的一种方法是采用多部分回答。所以它会发送一个空的HTML文件,以及附加的可下载文件。

例如:

Content-type: multipart/x-mixed-replace;boundary="abcde"

--abcde
Content-type: text/html

--abcde
Content-type: application/vnd.fdf
Content-Disposition: attachment; filename=foo.fdf

file-content
--abcde

这在Firefox中是有效的;它接收空HTML文件,触发“load”事件,然后显示可下载文件的“Save”对话框。但它在ie和Safari浏览器上无法运行;Internet Explorer触发“load”事件,但它不下载文件,而Safari下载文件(带有错误的名称和内容类型),但不触发“load”事件。

另一种方法可能是调用启动文件创建,轮询服务器直到准备就绪,然后下载已经创建的文件。但我宁愿避免在服务器上创建临时文件。

我该怎么办?


当前回答

问题是在生成文件时有一个“等待”指示器,然后在文件下载后恢复正常。我喜欢这样做的方式是使用一个隐藏的iFrame和钩子帧的onload事件,让我的页面知道什么时候开始下载。

但是onload不会在Internet Explorer中触发文件下载(就像使用附件头令牌一样)。轮询服务器是可行的,但我不喜欢这种额外的复杂性。这就是我所做的:

目标隐藏iFrame像往常一样。 生成内容。用 2分钟内绝对超时。 发送JavaScript重定向回 调用客户端,本质上调用 第二次生成页面。注意:这将导致在Internet Explorer中触发onload事件,因为它就像一个普通页面一样。 从缓存中删除内容并 发送给客户端。

免责声明:不要在繁忙的站点上这样做,因为缓存会增加。但实际上,如果您的站点非常繁忙,那么长时间运行的进程无论如何都会耗尽您的线程。

下面是隐藏代码的样子,这是您真正需要的。

public partial class Download : System.Web.UI.Page
{
    protected System.Web.UI.HtmlControls.HtmlControl Body;

    protected void Page_Load( object sender, EventArgs e )
    {
        byte[ ] data;
        string reportKey = Session.SessionID + "_Report";

        // Check is this page request to generate the content
        //    or return the content (data query string defined)
        if ( Request.QueryString[ "data" ] != null )
        {
            // Get the data and remove the cache
            data = Cache[ reportKey ] as byte[ ];
            Cache.Remove( reportKey );

            if ( data == null )
                // send the user some information
                Response.Write( "Javascript to tell user there was a problem." );
            else
            {
                Response.CacheControl = "no-cache";
                Response.AppendHeader( "Pragma", "no-cache" );
                Response.Buffer = true;

                Response.AppendHeader( "content-disposition", "attachment; filename=Report.pdf" );
                Response.AppendHeader( "content-size", data.Length.ToString( ) );
                Response.BinaryWrite( data );
            }
            Response.End();
        }
        else
        {
            // Generate the data here. I am loading a file just for an example
            using ( System.IO.FileStream stream = new System.IO.FileStream( @"C:\1.pdf", System.IO.FileMode.Open ) )
                using ( System.IO.BinaryReader reader = new System.IO.BinaryReader( stream ) )
                {
                    data = new byte[ reader.BaseStream.Length ];
                    reader.Read( data, 0, data.Length );
                }

            // Store the content for retrieval
            Cache.Insert( reportKey, data, null, DateTime.Now.AddMinutes( 5 ), TimeSpan.Zero );

            // This is the key bit that tells the frame to reload this page
            //   and start downloading the content. NOTE: Url has a query string
            //   value, so that the content isn't generated again.
            Body.Attributes.Add("onload", "window.location = 'binary.aspx?data=t'");
        }
    }

其他回答

如果您正在流式处理动态生成的文件,并且还实现了实时的服务器到客户端消息库,那么您可以非常容易地提醒客户端。

The server-to-client messaging library I like and recommend is Socket.io (via Node.js). After your server script is done generating the file that is being streamed for download your last line in that script can emit a message to Socket.io which sends a notification to the client. On the client, Socket.io listens for incoming messages emitted from the server and allows you to act on them. The benefit of using this method over others is that you are able to detect a "true" finish event after the streaming is done.

例如,您可以在单击下载链接后显示繁忙指示器,流式传输文件,向Socket发出消息。在您的流脚本的最后一行中,从服务器中输入io,在客户端侦听通知,接收通知并通过隐藏busy指示器更新您的UI。

我知道大多数读到这个问题答案的人可能没有这种类型的设置,但我已经在我自己的项目中使用了这种确切的解决方案,而且效果非常好。

套接字。IO非常容易安装和使用。查看更多信息:http://socket.io/

核心问题是web浏览器没有在页面导航被取消时触发事件,但有一个在页面完成加载时触发的事件。任何外部的直接浏览器事件都将是一个优点和缺点的黑客。

有四种已知的方法来处理检测浏览器下载何时开始:

调用fetch(),检索整个响应,附加带有下载属性的a标记,并触发单击事件。现代网络浏览器将为用户提供保存已经检索到的文件的选项。这种方法有几个缺点:

整个数据团存储在RAM中,因此如果文件很大,它将消耗同样多的RAM。对于小文件,这可能不是问题。 用户必须等待整个文件下载完成后才能保存。他们也不能离开页面,直到它完成。 未使用内置的web浏览器文件下载器。 除非设置了CORS报头,否则跨域获取可能会失败。

使用iframe +服务器端cookie。如果页面在iframe中加载而不是开始下载,iframe会触发一个加载事件,但如果下载开始,它不会触发任何事件。在web服务器上设置cookie可以被JavaScript循环检测到。这种方法有几个缺点:

服务器和客户机必须协同工作。服务器必须设置cookie。客户端必须检测cookie。 跨域请求将无法设置cookie。 每个域可以设置多少个cookie是有限制的。 不能发送自定义HTTP报头。

使用带有URL重定向的iframe。iframe启动一个请求,一旦服务器准备好文件,它将转储一个HTML文档,该文档执行元刷新到一个新的URL,这将在1秒后触发下载。iframe上的load事件发生在HTML文档加载时。这种方法有几个缺点:

服务器必须维护所下载内容的存储。需要cron作业或类似作业来定期清理目录。 当文件准备好时,服务器必须转储特殊的HTML内容。 在从DOM中删除iframe之前,客户端必须猜测iframe何时实际向服务器发出了第二个请求,以及下载实际何时开始。这可以通过将iframe留在DOM中来解决。 不能发送自定义HTTP报头。

Use an iframe + XHR. The iframe triggers the download request. As soon as the request is made via the iframe, an identical request via XHR is made. If the load event on the iframe fires, an error has occurred, abort the XHR request, and remove the iframe. If a XHR progress event fires, then downloading has probably started in the iframe, abort the XHR request, wait a few seconds, and then remove the iframe. This allows for larger files to be downloaded without relying on a server-side cookie. There are several downsides with this approach:

There are two separate requests made for the same information. The server can distinguish the XHR from the iframe by checking the incoming headers. A cross-domain XHR request will probably fail unless CORS headers are set. However, the browser won't know if CORS is allowed or not until the server sends back the HTTP headers. If the server waits to send headers until the file data is ready, the XHR can roughly detect when the iframe has started to download even without CORS. The client has to guess as to when the download has actually started to remove the iframe from the DOM. This could be overcome by just leaving the iframe in the DOM. Can't send custom headers on the iframe.

如果没有适当的内置web浏览器事件,这里就没有任何完美的解决方案。然而,根据您的用例,上述四种方法中的一种可能比其他方法更适合。

只要可能,动态地将响应流发送到客户端,而不是先在服务器上生成所有内容,然后再发送响应。各种文件格式可以流,如CSV, JSON, XML, ZIP等。这真的取决于找到一个支持流媒体内容的库。当请求一开始就流化响应时,检测下载的开始并不重要,因为它几乎马上就开始了。

另一种选择是预先输出下载标题,而不是等待所有内容先生成。然后生成内容,最后开始发送到客户端。用户内置的下载程序将耐心等待数据到达。缺点是底层网络连接可能会超时等待数据开始流动(无论是在客户端还是服务器端)。

我使用以下代码下载blobs并在下载后撤销对象URL。它在Chrome和Firefox中工作!

function download(blob){
    var url = URL.createObjectURL(blob);
    console.log('create ' + url);

    window.addEventListener('focus', window_focus, false);
    function window_focus(){
        window.removeEventListener('focus', window_focus, false);
        URL.revokeObjectURL(url);
        console.log('revoke ' + url);
    }
    location.href = url;
}

关闭文件下载对话框后,窗口将获得其焦点,因此将触发焦点事件。

我更新了下面的参考代码添加一个正确的下载URL链接并尝试一下。

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> body { padding: 0; margin: 0; } svg:not(:root) { display: block; } .playable-code { background-color: #F4F7F8; border: none; border-left: 6px solid #558ABB; border-width: medium medium medium 6px; color: #4D4E53; height: 100px; width: 90%; padding: 10px 10px 0; } .playable-canvas { border: 1px solid #4D4E53; border-radius: 2px; } .playable-buttons { text-align: right; width: 90%; padding: 5px 10px 5px 26px; } </style> <style type="text/css"> .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } </style> <title>XMLHttpRequest: progress event - Live_example - code sample</title> </head> <body> <div class="controls"> <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" /> <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> <script> const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { if (e.type == 'progress') { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred Received ${event.loaded} of ${event.total}\n`; } else if (e.type == 'loadstart') { log.textContent = log.textContent + `${e.type}: started\n`; } else if (e.type == 'error') { log.textContent = log.textContent + `${e.type}: error\n`; } else if (e.type == 'loadend') { log.textContent = log.textContent + `${e.type}: completed\n`; } } function addListeners(xhr) { xhr.addEventListener('loadstart', handleEvent); xhr.addEventListener('load', handleEvent); xhr.addEventListener('loadend', handleEvent); xhr.addEventListener('progress', handleEvent); xhr.addEventListener('error', handleEvent); xhr.addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); var request = new XMLHttpRequest(); addListeners(request); request.open('GET', url, true); request.responseType = 'blob'; request.onload = function (e) { var data = request.response; var blobUrl = window.URL.createObjectURL(data); var downloadLink = document.createElement('a'); downloadLink.href = blobUrl; downloadLink.download = 'download.zip'; downloadLink.click(); }; request.send(); return request } xhrButtonSuccess.addEventListener('click', () => { runXHR('https://abbbbbc.com/download.zip'); }); xhrButtonError.addEventListener('click', () => { runXHR('http://i-dont-exist'); }); xhrButtonAbort.addEventListener('click', () => { runXHR('https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json').abort(); }); </script> </body> </html> Return to post

参考:XMLHttpRequest:进度事件,实时示例

我在这个配置中遇到了同样的问题:

Struts 1.2.9 jQuery 1.3.2。 jQuery UI 1.7.1.custom Internet Explorer 11 Java 5

我用饼干的解决方案:

客户端:

在提交表单时,调用JavaScript函数隐藏页面并加载等待的旋转器

function loadWaitingSpinner() {
    ... hide your page and show your spinner ...
}

然后,调用一个函数,每500毫秒检查一次cookie是否来自服务器。

function checkCookie() {
    var verif = setInterval(isWaitingCookie, 500, verif);
}

如果找到cookie,停止每500毫秒检查一次,使cookie过期并调用函数返回页面并删除等待spinner (removeWaitingSpinner())。如果您希望能够再次下载另一个文件,过期cookie是很重要的!

function isWaitingCookie(verif) {
    var loadState = getCookie("waitingCookie");
    if (loadState == "done") {
        clearInterval(verif);
        document.cookie = "attenteCookie=done; expires=Tue, 31 Dec 1985 21:00:00 UTC;";
        removeWaitingSpinner();
    }
}

function getCookie(cookieName) {
    var name = cookieName + "=";
    var cookies = document.cookie
    var cs = cookies.split(';');
    for (var i = 0; i < cs.length; i++) {
        var c = cs[i];
        while(c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function removeWaitingSpinner() {
    ... come back to your page and remove your spinner ...
}

服务器端:

在服务器进程结束时,向响应添加一个cookie。当您的文件准备好下载时,cookie将被发送到客户端。

Cookie waitCookie = new Cookie("waitingCookie", "done");
response.addCookie(waitCookie);