2017-11-25 146 views
0

请有人告诉我如何显示从服务器发送字节到浏览器的总文件大小和下载时间。 我试图通过字节到client.Here发送大量字节(1 GB)字节是我试图代码:下载文件不显示总文件大小和时间(C#)

long dataToRead; 
int length; 
byte[] buffer = new Byte[100000]; 
FileStream iStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); 

dataToRead = iStream.Length; 
Response.ContentType = "application/octet-stream"; 
Response.AddHeader("Content-Disposition", "attachment; filename=" + file); 
while (dataToRead > 0) 
{ 
    // Verify that the client is connected. 
    if (Response.IsClientConnected) 
    { 
     // Read the data in buffer. 
     length = iStream.Read(buffer, 0, 10000); 

     // Write the data to the current output stream. 
     await Response.OutputStream.WriteAsync(buffer, 0, length); 

     // Flush the data to the HTML output. 
     Response.Flush(); 

     buffer = new Byte[100000]; 
     dataToRead = dataToRead - length; 
    } 
    else 
    { 
     dataToRead = -1; 
    } 
} 
+1

请注意,在您的代码示例中,即使在服务器端,您也不知道文件有多大。您希望如何告知客户并根据总规模报告进度? –

+0

什么是手动编码的浪费。你为什么不使用'返回FileStream(iStream)'? –

+0

谢谢@凯尔伯恩斯您的回复,我只是想要的代码,请你帮我写这样的代码 –

回答

0

你可以尝试添加一个Content-Length头让浏览器知道大小是什么:

Response.ContentType = "application/octet-stream"; 
Response.AddHeader("Content-Length", dataToRead.ToString()); 
// Remainder of your code 
+0

感谢@Nikola的代码 –