下载功能在下载时不显示文件的总大小
本文关键字:下载 功能 显示文件 | 更新日期: 2023-09-27 18:25:57
protected void downloadFunction(string filename)
{
string filepath = @"D:'XtraFiles'" + filename;
string contentType = "application/x-newton-compatible-pkg";
Stream iStream = null;
// Buffer to read 1024K bytes in chunk
byte[] buffer = new Byte[1048576];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
try
{
// Open the file.
iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (HttpContext.Current.Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
HttpContext.Current.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
HttpContext.Current.Response.Write("Error : " + ex.Message + "<br />");
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("Error : file not found");
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
HttpContext.Current.Response.End();
HttpContext.Current.Response.Close();
}
}
我的 donwload 功能运行良好,但是当用户下载时,浏览器看不到下载的总文件大小。
所以现在浏览器说 eq. 下载 8mb 的 ?,而不是下载 8mb 的 142mb。
我错过了什么?
内容长度标题似乎是您缺少的。
如果您设置了此设置,浏览器将知道期望多少。否则,它只会一直持续到您停止发送数据为止,并且直到最后都不知道需要多长时间。
Response.AddHeader("Content-Length", iStream.Length);
您可能还对Response.WriteFile
感兴趣,它可以提供一种更简单的方法将文件发送到客户端,而不必担心流。
你需要
发送一个ContentLength
-Header:
HttpContext.Current.Response.AddHeader(HttpRequestHeader.ContentLength, iStream.Length);