2012-02-28 171 views
0
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。

我錯過了什麼?

+0

風格危險......「什麼是內容長度標題?」 – 2012-02-28 10:36:05

+0

順便說一句,你應該能夠使用TransmitFile或類似的;無需編寫此代碼 - 並且該緩衝區大大超大 – 2012-02-28 10:37:43

回答

1

Content-Length header似乎是你錯過了什麼。

如果你設置了這個,瀏覽器就會知道你有多少期待。否則,它會繼續前進,直到停止發送數據,並且直到最後才知道它會持續多久。

Response.AddHeader("Content-Length", iStream.Length); 

您還可能有興趣在Response.WriteFile whcih可以提供將文件發送給客戶端的更簡單的方法,而不必擔心自己的數據流。

0

您需要發送一個ContentLength -Header:

HttpContext.Current.Response.AddHeader(HttpRequestHeader.ContentLength, iStream.Length); 
+0

HttpContext.Current.Response.AddHeader(「Content-Length」,iStream.Length.ToString());訣竅:) – 2012-02-28 10:41:00