您将需要在客户端上使用一些 javascript 来获得您想要的结果。我从这里https://stackoverflow.com/a/4168965/1002621获取了基础知识,这是一个带有 php 后端的示例。
您需要在客户端上的代码看起来像这样基本前提是您使用 jquery 来拦截您的下载按钮单击事件,以便可以将令牌注入表单帖子中,然后您可以在响应中发送回以了解文件下载完成,然后做你自己的表单提交/无论什么。
<script type="text/javascript">
function DownloadAndRefresh() {
//get form and inject a hidden token input
var form = $(this).closest('form');
var tokenInput = $('input[name=token]');
if (tokenInput.length == 0) {
tokenInput = $('<input />').prop('type', 'hidden').prop('name', 'token');
form.append(tokenInput);
}
//create a unqiue token we can watch for and set the hidden inputs value
var token = new Date().getTime();
tokenInput.prop('value', token);
//watch for the token to come back in the documents cookie (this is set on server)
var tokenInterval = setInterval(function () {
//check to see if the cookie contains the token yet
if (document.cookie.indexOf(token) != -1) {
//submit the form again now the file has been downloaded (this causes a standard postback)
form[0].submit();
window.clearInterval(tokenInterval);
}
}, 200);
//wait up to 60 seconds for the token then stop the interval because something probably went wrong
setTimeout(function () { window.clearInterval(tokenInterval); }, 60000);
//allow the current post action to continue
return true;
}
$(document).ready(function () {
//call the DownloadAndRefresh function before posting to the server
$('#<%= DownloadButton.ClientID %>').on('click', DownloadAndRefresh);
});
</script>
<asp:Button runat="server" ID="DownloadButton" Text="Download Button" onclick="Download_Click" />
服务器代码非常简单,只需要从请求表单中提取令牌并将其放入响应 cookie 中。
protected void Download_Click(object sender, EventArgs e)
{
Response.Clear();
//set the response token cookie to be the token sent in the form request
Response.SetCookie(new HttpCookie("token", Request.Form["token"]));
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=file.txt");
Response.ContentType = "text/plain";
Response.Output.Write("some text");
Response.End();
}