您只能在一个请求/响应周期中发送或传输1个MIME类型。 (我在这方面的知识是有争议的)。
这就是说,你可以设计一个破解这个。在客户端上使用iframe来“下载文件”。您可以将它的src
指向一个相同的ashx文件。
您需要连接iframe的onload事件,以便您的网页知道下载已完成;那就是你可以执行你的逻辑的地方。
解决方案更新:
好,周围挖掘后,我“已经发现了我的答案是半生不熟!
问题是iframe在下载内容后不会触发它们的onload事件。如果存在src
指向的url实际导航到不同的页面,onload事件将触发。这是我设想的。我今天学到了!
那么,解决方法是什么?
幸运的是,您可以将cookie传输给客户端。在客户端上,您的网页必须保持对该cookie的存在进行轮询。因此,一旦您的网页能够检测到cookie的存在,这意味着浏览器已完成下载请求。这已经很详细下面帖子中讨论:
http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx
我就告诉你有关处理程序文件(模拟下载)一些代码,并在客户端(其中有一个iframe做工作)。这应该非常给你要点:
WebForm1.aspx的:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.FileDownload.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iFrame Download</title>
<script type="text/javascript" src="Scripts/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.cookie.js"></script>
<script type="text/javascript">
function foo() {
console.log('foo');
//execute post-download logic here
}
$(function() {
$('input').click(function() {
//make sure we get rid of the
//cookie before download
$.removeCookie('downloaded');
var intrvl = setTimeout(function() { //this function polls for the cookie through which we track that the file has indeed been downloaded
console.log('timer');
var value = $.cookie('downloaded');
if (value == 'true') {
clearTimeout(intrvl);
foo();
}
}, 1000);
//this initiates the download
$('iframe').attr({
'src': 'download.ashx?id=' + $('#tbxRandomNumber').val()
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="tbxRandomNumber" runat="server"></asp:TextBox>
<input type="button" value="Download" />
<iframe src="about:blank" style="display:none"></iframe>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Next Random Number" />
</div>
</form>
</body>
</html>
我做了使用jquery cookies plugin帮我处理Cookie。
download.ashx:
using System;
using System.Web;
namespace WebApp.FileDownload
{
/// <summary>
/// Summary description for download
/// </summary>
public class download : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.SetCookie(new HttpCookie("downloaded","true")); //setting cookie in the response
string id = context.Request.QueryString["id"] == null ? "NULL" : context.Request.QueryString["id"];
string str = string.Format("Content with id {0} was generated at {1}", id, DateTime.Now.ToLongTimeString());
context.Response.AddHeader("Content-Disposition", "attachment; filename=test.txt");
context.Response.AddHeader("Content-Length", str.Length.ToString());
context.Response.Write(str);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
你是不是在这里发送的HTML页面。浏览器正在接收excel文档或将其提供给用户下载,因此没有页面。没有页面 - 没有JavaScript被执行。 – Andrei
@Andrei,我看到谢谢你。 – gg17