我正在尝试解决当前项目中的以下问题。
现有
aspx
页面上有一个按钮,它有一个服务器端点击事件。我们根据所选的gridview行在此事件中进行一些处理,并根据所选记录向浏览器显示文件下载对话框。
要更改的功能
如果在处理过程中有任何记录失败,那么我们希望提示用户“处理过程中存在少数选定记录的错误”。你想继续下载文件吗?“
方法我试图解决这个问题
我从服务器端button_click
事件触发jquery函数以显示jquery对话框,以通知用户在处理过程中存在一些选定记录的错误。
ClientScript.RegisterStartupScript(GetType(), "Popup", "ShowPopup();", true);
我使用Ajax调用webmethod,执行以下代码:
response.Clear();
response.ContentType = "Application/Octet-Stream";
response.AddHeader("Content-Disposition",
string.Format("Attachment; FileName={0}", Path.GetFileName(filePath)));
response.WriteFile(filePath);
response.End();
结果
我得到了弹出窗口,web方法也正常运行,但我没有在浏览器中看到任何文件下载对话框。我怀疑response.end
在这种情况下不起作用。
答案 0 :(得分:0)
您无法通过AJAX下载文件。它必须通过链接点击进行表单提交或GET请求。 Response.End
运行正常:您不只是在ASP.NET中找到了一个错误。
答案 1 :(得分:0)
如果你想通过javascript下载文件你可以用API端点返回的文件做这样的事情,这段代码使用了一个角度调用,但是没有它也可以完成:
// Make an api call with the responseType of blob and do this with the result
const blob = new Blob([result], { type: result.type });
if ($window.navigator.msSaveOrOpenBlob) {
$window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
const fileURL = URL.createObjectURL(blob);
const downloadLink = angular.element('<a></a>');// create a new <a> tag element
downloadLink.attr('href', fileURL);
downloadLink.attr('download', fileName);
downloadLink.attr('target', '_self');
downloadLink[0].click();// call click function
URL.revokeObjectURL(fileURL);// revoke the object from URL
}