您只能在一个请求/响应周期中发送或传输 1 个 mime 类型。 (我在这方面的知识值得商榷)。
也就是说,您可以围绕此设计一个 hack。在客户端上使用 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。
下载.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;
}
}
}
}