检测浏览器何时收到文件下载

问题描述 投票:437回答:17

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

我正在以隐藏的形式发出请求,该请求POST到服务器,并针对其结果定位隐藏的iframe。这样我就不会用结果替换整个浏览器窗口。我在iframe上监听“加载”事件,希望在下载完成后它会触发。

我在文件中返回“Content-Disposition:attachment”标题,这会导致浏览器显示“保存”对话框。但浏览器不会在iframe中触发“加载”事件。

我尝试过的一种方法是使用多部分响应。因此它会发送一个空的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上失败了; IE触发“加载”事件但不下载文件,Safari下载文件(名称和内容类型错误),并且不会触发“加载”事件。

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

有没有人有更好的主意?

javascript http mime
17个回答
422
投票

一个possible solution在客户端上使用JavaScript。

客户端算法:

  1. 生成随机唯一标记。
  2. 提交下载请求,并将令牌包含在GET / POST字段中。
  3. 显示“等待”指标。
  4. 启动一个计时器,每隔一秒左右,找一个名为“fileDownloadToken”的cookie(或你决定的任何东西)。
  5. 如果cookie存在,并且其值与令牌匹配,则隐藏“等待”指示符。

服务器算法:

  1. 在请求中查找GET / POST字段。
  2. 如果它具有非空值,则删除cookie(例如“fileDownloadToken”),并将其值设置为令牌的值。

客户端源代码(JavaScript):

function getCookie( name ) {
  var parts = document.cookie.split(name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

function expireCookie( cName ) {
    document.cookie = 
        encodeURIComponent(cName) + "=deleted; expires=" + new Date( 0 ).toUTCString();
}

function setCursor( docStyle, buttonStyle ) {
    document.getElementById( "doc" ).style.cursor = docStyle;
    document.getElementById( "button-id" ).style.cursor = buttonStyle;
}

function setFormToken() {
    var downloadToken = new Date().getTime();
    document.getElementById( "downloadToken" ).value = downloadToken;
    return downloadToken;
}

var downloadTimer;
var attempts = 30;

// Prevents double-submits by waiting for a cookie from the server.
function blockResubmit() {
    var downloadToken = setFormToken();
    setCursor( "wait", "wait" );

    downloadTimer = window.setInterval( function() {
        var token = getCookie( "downloadToken" );

        if( (token == downloadToken) || (attempts == 0) ) {
            unblockSubmit();
        }

        attempts--;
    }, 1000 );
}

function unblockSubmit() {
  setCursor( "auto", "pointer" );
  window.clearInterval( downloadTimer );
  expireCookie( "downloadToken" );
  attempts = 30;
}

示例服务器代码(PHP):

$TOKEN = "downloadToken";

// Sets a cookie so that when the download begins the browser can
// unblock the submit button (thus helping to prevent multiple clicks).
// The false parameter allows the cookie to be exposed to JavaScript.
$this->setCookieToken( $TOKEN, $_GET[ $TOKEN ], false );

$result = $this->sendFile();

哪里:

public function setCookieToken(
    $cookieName, $cookieValue, $httpOnly = true, $secure = false ) {

    // See: http://stackoverflow.com/a/1459794/59087
    // See: http://shiflett.org/blog/2006/mar/server-name-versus-http-host
    // See: http://stackoverflow.com/a/3290474/59087
    setcookie(
        $cookieName,
        $cookieValue,
        2147483647,            // expires January 1, 2038
        "/",                   // your path
        $_SERVER["HTTP_HOST"], // your domain
        $secure,               // Use true over HTTPS
        $httpOnly              // Set true for $AUTH_COOKIE_NAME
    );
}

3
投票

我参加派对的时间已经很晚了,但如果有人想知道我的解决方案,我会把它放在这里:

我对这个确切的问题真的很挣扎,但我找到了一个使用iframe的可行解决方案(我知道,我知道。这很糟糕,但它适用于我遇到的一个简单问题)

我有一个html页面,它启动了一个单独的php脚本,生成该文件,然后下载它。在html页面上,我在html标头中使用了以下jquery(你还需要包含一个jquery库):

<script>
    $(function(){
        var iframe = $("<iframe>", {name: 'iframe', id: 'iframe',}).appendTo("body").hide();
        $('#click').on('click', function(){
            $('#iframe').attr('src', 'your_download_script.php');
        });
        $('iframe').load(function(){
            $('#iframe').attr('src', 'your_download_script.php?download=yes'); <!--on first iframe load, run script again but download file instead-->
            $('#iframe').unbind(); <!--unbinds the iframe. Helps prevent against infinite recursion if the script returns valid html (such as echoing out exceptions) -->
        });
    });
</script>

在your_download_script.php上,有以下内容:

function downloadFile($file_path) {
    if (file_exists($file_path)) {
        header('Content-Description: File Transfer');
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename=' . basename($file_path));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file_path));
        ob_clean();
        flush();
        readfile($file_path);
        exit();
    }
}


$_SESSION['your_file'] = path_to_file; //this is just how I chose to store the filepath

if (isset($_REQUEST['download']) && $_REQUEST['download'] == 'yes') {
    downloadFile($_SESSION['your_file']);
} else {
    *execute logic to create the file*
}

为了解决这个问题,jquery首先在iframe中启动你的php脚本。生成文件后加载iframe。然后jquery再次使用请求变量启动脚本,告诉脚本下载文件。

你无法一次性完成下载和文件生成的原因是由于php header()函数。如果使用header(),则将脚本更改为网页以外的其他内容,而jquery永远不会将下载脚本识别为“已加载”。我知道这可能不一定会在浏览器收到文件时检测到,但您的问题听起来与我的相似。


2
投票

我刚才遇到了同样的问题。我的解决方案是使用临时文件,因为我已经生成了一堆临时文件。表格提交时:

var microBox = {
    show : function(content) {
        $(document.body).append('<div id="microBox_overlay"></div><div id="microBox_window"><div id="microBox_frame"><div id="microBox">' +
        content + '</div></div></div>');
        return $('#microBox_overlay');
    },

    close : function() {
        $('#microBox_overlay').remove();
        $('#microBox_window').remove();
    }
};

$.fn.bgForm = function(content, callback) {
    // Create an iframe as target of form submit
    var id = 'bgForm' + (new Date().getTime());
    var $iframe = $('<iframe id="' + id + '" name="' + id + '" style="display: none;" src="about:blank"></iframe>')
        .appendTo(document.body);
    var $form = this;
    // Submittal to an iframe target prevents page refresh
    $form.attr('target', id);
    // The first load event is called when about:blank is loaded
    $iframe.one('load', function() {
        // Attach listener to load events that occur after successful form submittal
        $iframe.load(function() {
            microBox.close();
            if (typeof(callback) == 'function') {
                var iframe = $iframe[0];
                var doc = iframe.contentWindow.document;
                var data = doc.body.innerHTML;
                callback(data);
            }
        });
    });

    this.submit(function() {
        microBox.show(content);
    });

    return this;
};

$('#myForm').bgForm('Please wait...');

在生成我拥有的文件的脚本的末尾:

header('Refresh: 0;url=fetch.php?token=' . $token);
echo '<html></html>';

这将导致iframe上的load事件被触发。然后关闭等待消息,然后开始文件下载。在IE7和Firefox上测试过。


1
投票

如果您下载的文件已保存,而不是在文档中,则无法确定下载何时完成,因为它不在当前文档的范围内,而是在浏览器中的单独进程。


1
投票

“如何检测浏览器何时收到文件下载?” 我遇到了与该配置相同的问题: 支柱1.2.9 jQuery的1.3.2。 jQuery的UI,1.7.1.custom IE 11 java 5

我用cookie的解决方案: - 客户端: 提交表单时,请调用javascript函数隐藏页面并加载等待的微调器

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

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

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

如果找到cookie,则每隔500ms停止检查一次,使cookie过期并调用您的函数返回到您的页面并删除等待的微调器(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);

我希望能帮助别人!


0
投票

问题是在生成文件时有一个“等待”指示符,然后在文件下载后恢复正常。我喜欢todo的方式是使用隐藏的iFrame并挂钩框架的onload事件,以便在下载开始时让我的页面知道。但是在IE中不会触发onload以进行文件下载(例如附件标头令牌)。轮询服务器有效,但我不喜欢额外的复杂性。所以这就是我的所作所为:

  • 像往常一样定位隐藏的iFrame。
  • 生成内容。在2分钟内使用绝对超时缓存它。
  • 将javascript重定向发送回调用客户端,实质上是第二次调用生成器页面。注意:这将导致onload事件在IE中触发,因为它的行为类似于常规页面。
  • 从缓存中删除内容并将其发送到客户端。

免责声明,不要在繁忙的网站上这样做,因为缓存可能会加起来。但实际上,如果您的网站忙于长时间运行的过程,那么无论如何都会让您失去线程。

这就是代码隐藏的样子,这就是你真正需要的。

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'");
        }
    }

0
投票

如果您只想在显示下载对话框之前显示消息或加载程序gif,则快速解决方案是将消息放入隐藏容器中,当您单击生成要下载的文件的按钮时,可以使容器可见。然后使用jquery或javascript来捕获按钮的focusout事件以隐藏包含消息的容器


0
投票

如果带有blob的Xmlhttprequest不是一个选项,那么您可以在新窗口中打开文件,并检查eny元素是否以间隔填充在该窗口主体中。

var form = document.getElementById("frmDownlaod");
 form.setAttribute("action","downoad/url");
 form.setAttribute("target","downlaod");
 var exportwindow = window.open("", "downlaod", "width=800,height=600,resizable=yes");
 form.submit();

var responseInterval = setInterval(function(){
	var winBody = exportwindow.document.body
	if(winBody.hasChildNodes()) // or 'downoad/url' === exportwindow.document.location.href
	{
		clearInterval(responseInterval);
		// do your work
		// if there is error page configured your application for failed requests, check for those dom elemets 
	}
}, 1000)
//Better if you specify maximun no of intervals

-2
投票

单击按钮/链接时创建iframe并将其附加到正文。

                  $('<iframe />')
                 .attr('src', url)
                 .attr('id','iframe_download_report')
                 .hide()
                 .appendTo('body'); 

创建一个延迟的iframe,并在下载后删除它。

                            var triggerDelay =   100;
                            var cleaningDelay =  20000;
                            var that = this;
                            setTimeout(function() {
                                var frame = $('<iframe style="width:1px; height:1px;" class="multi-download-frame"></iframe>');
                                frame.attr('src', url+"?"+ "Content-Disposition: attachment ; filename="+that.model.get('fileName'));
                                $(ev.target).after(frame);
                                setTimeout(function() {
                                    frame.remove();
                                }, cleaningDelay);
                            }, triggerDelay);

27
投票

一个非常简单(和蹩脚)的单行解决方案是使用window.onblur()事件来关闭加载对话框。当然,如果花费太长时间并且用户决定做其他事情(比如阅读电子邮件),则加载对话框将关闭。


12
投票

老线程,我知道......

但那些谷歌引领的人可能会对我的解决方案感兴趣。它非常简单,但又可靠。它可以显示真实的进度消息(并且可以轻松插入现有进程):

处理的脚本(我的问题是:通过http检索文件并将其作为zip传递)将状态写入会话。

每秒轮询和显示状态。这就是全部(好吧,不是。你必须处理很多细节[例如并发下载],但它是一个很好的起点;-))。

下载页面:

    <a href="download.php?id=1" class="download">DOWNLOAD 1</a>
    <a href="download.php?id=2" class="download">DOWNLOAD 2</a>
    ...
    <div id="wait">
    Please wait...
    <div id="statusmessage"></div>
    </div>
    <script>
//this is jquery
    $('a.download').each(function()
       {
        $(this).click(
             function(){
               $('#statusmessage').html('prepare loading...');
               $('#wait').show();
               setTimeout('getstatus()', 1000);
             }
          );
        });
    });
    function getstatus(){
      $.ajax({
          url: "/getstatus.php",
          type: "POST",
          dataType: 'json',
          success: function(data) {
            $('#statusmessage').html(data.message);
            if(data.status=="pending")
              setTimeout('getstatus()', 1000);
            else
              $('#wait').hide();
          }
      });
    }
    </script>

getstatus.php

<?php
session_start();
echo json_encode($_SESSION['downloadstatus']);
?>

的download.php

    <?php
    session_start();
    $processing=true;
    while($processing){
      $_SESSION['downloadstatus']=array("status"=>"pending","message"=>"Processing".$someinfo);
      session_write_close();
      $processing=do_what_has_2Bdone();
      session_start();
    }
      $_SESSION['downloadstatus']=array("status"=>"finished","message"=>"Done");
//and spit the generated file to the browser
    ?>

10
投票

我使用以下内容下载blob并在下载后撤消object-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;
}

关闭文件下载对话框后,窗口会将焦点恢复,以便触发焦点事件。


8
投票

我写了一个简单的JavaScript类,它实现了一种类似于背叛answer中描述的技术。我希望这对某人有用。 GitHub项目名为response-monitor.js

默认情况下,它使用spin.js作为等待指标,但它还提供了一组用于实现自定义指标的回调。

支持JQuery但不是必需的。

值得注意的功能

  • 简单集成
  • 没有依赖
  • JQuery插件(可选)
  • Spin.js集成(可选)
  • 用于监视事件的可配置回调
  • 处理多个同时请求
  • 服务器端错误检测
  • 超时检测
  • 跨浏览器

用法示例

HTML

<!-- the response monitor implementation -->
<script src="response-monitor.js"></script>

<!-- optional JQuery plug-in -->
<script src="response-monitor.jquery.js"></script> 

<a class="my_anchors" href="/report?criteria1=a&criteria2=b#30">Link 1 (Timeout: 30s)</a>
<a class="my_anchors" href="/report?criteria1=b&criteria2=d#10">Link 2 (Timeout: 10s)</a>

<form id="my_form" method="POST">
    <input type="text" name="criteria1">
    <input type="text" name="criteria2">
    <input type="submit" value="Download Report">
</form>

客户端(纯JavaScript)

//registering multiple anchors at once
var my_anchors = document.getElementsByClassName('my_anchors');
ResponseMonitor.register(my_anchors); //clicking on the links initiates monitoring

//registering a single form
var my_form = document.getElementById('my_form');
ResponseMonitor.register(my_form); //the submit event will be intercepted and monitored

客户端(JQuery)

$('.my_anchors').ResponseMonitor();
$('#my_form').ResponseMonitor({timeout: 20});

带回调的客户端(JQuery)

//when options are defined, the default spin.js integration is bypassed
var options = {
    onRequest: function(token){
        $('#cookie').html(token);
        $('#outcome').html('');
        $('#duration').html(''); 
    },
    onMonitor: function(countdown){
        $('#duration').html(countdown); 
    },
    onResponse: function(status){
        $('#outcome').html(status==1?'success':'failure');
    },
    onTimeout: function(){
        $('#outcome').html('timeout');
    }
};

//monitor all anchors in the document
$('a').ResponseMonitor(options);

服务器(PHP)

$cookiePrefix = 'response-monitor'; //must match the one set on the client options
$tokenValue = $_GET[$cookiePrefix];
$cookieName = $cookiePrefix.'_'.$tokenValue; //ex: response-monitor_1419642741528

//this value is passed to the client through the ResponseMonitor.onResponse callback
$cookieValue = 1; //for ex, "1" can interpret as success and "0" as failure

setcookie(
    $cookieName,
    $cookieValue,
    time()+300,            // expire in 5 minutes
    "/",
    $_SERVER["HTTP_HOST"],
    true,
    false
);

header('Content-Type: text/plain');
header("Content-Disposition: attachment; filename=\"Response.txt\"");

sleep(5); //simulate whatever delays the response
print_r($_REQUEST); //dump the request in the text file

有关更多示例,请检查存储库中的examples文件夹。


5
投票

根据埃尔默的例子,我已经准备好了自己的解决方案。使用已定义的下载类单击元素后,可以在屏幕上显示自定义消息。我使用焦点触发来隐藏消息。

JavaScript的

$(function(){$('.download').click(function() { ShowDownloadMessage(); }); })

function ShowDownloadMessage()
{
     $('#message-text').text('your report is creating, please wait...');
     $('#message').show();
     window.addEventListener('focus', HideDownloadMessage, false);
}

function HideDownloadMessage(){
    window.removeEventListener('focus', HideDownloadMessage, false);                   
    $('#message').hide();
}

HTML

<div id="message" style="display: none">
    <div id="message-screen-mask" class="ui-widget-overlay ui-front"></div>
    <div id="message-text" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable waitmessage">please wait...</div>
</div>

现在您应该实现要下载的任何元素:

<a class="download" href="file://www.ocelot.com.pl/prepare-report">Download report</a>

要么

<input class="download" type="submit" value="Download" name="actionType">

每次下载后,您都会看到报告正在创建的消息,请稍候...


5
投票

如果您正在流式传输动态生成的文件,并且还实现了实时的服务器到客户端消息库,则可以非常轻松地向客户端发出警报。

我喜欢并推荐的服务器到客户端消息传递库是Socket.io(通过Node.js)。在完成服务器脚本生成要流下载的文件后,该脚本中的最后一行可以向Socket.io发送一条消息,向客户端发送通知。在客户端上,Socket.io侦听从服务器发出的传入消息,并允许您对它们进行操作。使用此方法优于其他方法的好处是,您可以在完成流式传输后检测到“真正的”完成事件。

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

我意识到大多数人阅读这个问题的答案可能没有这种类型的设置,但我已经使用这个确切的解决方案在我自己的项目中产生了很大的效果,它的工作非常好。

Socket.io非常容易安装和使用。查看更多:http://socket.io/


3
投票

当用户触发文件生成时,您只需为该“下载”分配一个唯一ID,并将用户发送到每隔几秒刷新(或使用AJAX检查)的页面。文件完成后,将其保存在相同的唯一ID下...

  • 如果文件准备就绪,请进行下载。
  • 如果文件尚未就绪,请显示进度。

然后你可以跳过整个iframe / waiting / browserwindow混乱,但有一个非常优雅的解决方案。


3
投票

如果您不想在服务器上生成和存储文件,是否愿意存储状态,例如文件正在进行中,文件完整?您的“等待”页面可以轮询服务器以了解文件生成何时完成。你不确定浏览器是否开始下载,但你有信心。

© www.soinside.com 2019 - 2024. All rights reserved.