javascript - 使用 XMLHttpRequest 下载文件后如何显示消息?
问题描述
您好社区我希望您能帮助我,因为我在下载 excel 文件后无法向用户显示消息。
我正在使用 httpRequest 向服务器发送数据,并且一切正常,文件已下载,但我还想要显示消息。
非常感谢您的帮助。
这是我的代码 javaScript。
function download_excel_file() {
var file_name; //Example Test.xlsx
var parameter = '{file_name:"' + file_name + '"}';
var url = "Download.aspx/Download_File";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
var a;
if (xhr.readyState === 4 && xhr.status === 200) {
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response);
a.download = file_name;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// Here I want to show the message with the legend = File downloaded successfully but it does not work.
$("[id*=message_download]").css("display","block");
$("[id*=message_download]").text(xhr.response.Text);
}
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.responseType = 'blob';
xhr.send(parameter);
}
<input id="btn_download_file" type="button" value="Download file" class="btn btn-success btn-block" onclick="return download_excel_file();"/>
<div id="message_download" class="p-3 mb-1 bg-secondary text-white text-center" style="display:none"> </div>
这是我来自服务器的代码。
[WebMethod]
public static void Download_File(string file_name)
{
if (file_name != null || file_name != "")
{
string path = HttpContext.Current.Server.MapPath("~/Folder_Excel/" + file_name);
if (File.Exists(path))
{
// This is the message I want to show in the div $("[id*=message_download]")
HttpContext.Current.Response.Write("File downloaded successfully");
System.IO.FileStream fs = null;
fs = System.IO.File.Open(path, System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=" + file_name);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(btFile);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
else
{
HttpContext.Current.Response.Write("No files");
}
}
}
解决方案
您应该首先显示您的消息,然后让浏览器“点击”下载按钮。否则浏览器可能会触发一个unload
事件并在此时停止执行任何脚本——比如重定向。
推荐阅读
- python - 从 Python 中的循环输出中删除重复的结果
- c# - Selenium - 如何断言该字段等于 0
- c# - 从 C# 中的子域/其他域加载图像
- c# - c#在数据网格视图中突出显示单元格,其中一个特定单元格是重复的,任何其他单元格都是重复的
- java - java拆分日期时间段并返回数组
- javascript - 何时使用 const 或 var 或 let 和 lambda 表达式内部
- pandas - 如何解包列表项的索引对
- blockchain - HD钱包(bip32)地址派生路径
- javascript - 如何使用类选择器仅执行选定元素的单击事件
- .net - 如果我的数据库服务器宕机了一段时间,我每次都必须重置 IIS 才能重新建立连接