2009-05-20 67 views
1

我正在使用HttpHandler向用戶發送文件。在所有瀏覽器上,在查看/下載文件至少一次之後,瀏覽器/應用程序在隨後的視圖/下載中會掛起。這裏是代碼:通過HttpContext發送文件會導致瀏覽器掛起

private void TransmitFile(HttpContext context, string filePath, string downloadName, bool forceDownload) 
    { 
     if (File.Exists(filePath)) 
     { 
      string fileName = System.IO.Path.GetFileName(filePath); 
      string extension = Path.GetExtension(filePath); 
      FileInfo fileInfo = new FileInfo(filePath); 

      // set the response info/headers 
      context.Response.ClearContent(); 
      context.Response.ClearHeaders(); 
      context.Response.AddHeader("Content-Length", fileInfo.Length.ToString()); 
      if (forceDownload) 
      { 
       context.Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName.Replace(" ", "_") + extension); 
       context.Response.BufferOutput = false; 
      } 

      string type = ""; 
      // set known types based on file extension 
      if (extension != null) 
      { 
       switch (extension.ToLower()) 
       { 
        case ".tif": 
        case ".tiff": 
         type = "image/tiff"; 
         break; 
        case ".jpg": 
        case ".jpeg": 
         type = "image/jpeg"; 
         break; 
        case ".gif": 
         type = "image/gif"; 
         break; 
        case ".doc": 
        case ".rtf": 
         type = "Application/msword"; 
         break; 
        case "pdf": 
         type = "Application/pdf"; 
         break; 
        case "png": 
         type = "image/png"; 
         break; 
        case "bmp": 
         type = "image/bmp"; 
         break; 
        default: 
         type = "application/octet-stream"; 
         break; 
       } 
      } 

      context.Response.ContentType = type; 
      context.Response.TransmitFile(filePath); 
      context.Response.Flush(); 
     } 
     else 
     { 
      Immersive.Diagnostics.Log.Warn("Requested file does not exist: " + filePath, this); 
      Immersive.Diagnostics.Log.Warn("", this); 
     } 
    } 

我讀過,調用Response.Close()和Response.End()不是一個好主意?已經嘗試了兩個離開,並刪除,它仍然發生。

編輯:

似乎已的TransmitFile已知問題。更詳細的解釋可以在: http://www.improve.dk/blog/2008/03/29/response-transmitfile-close-will-kill-your-application

我刪除了TransmitFile並更改爲WriteFile,現在它完美工作。

context.Response.WriteFile(filePath); 
context.Response.Flush(); 
context.Response.Close(); 

回答

0

如果您從中下載的服務器運行Windows Server 2003 SP1,則這可能是已知問題。

這裏是一個修補程序:http://support.microsoft.com/kb/902780

此外,檢查是否有在頁面上啓用OutputCache,如果是這樣,請嘗試重新下載沒有它。

0

任何你沒有使用緩衝的原因?即使你沒有使用它,你也會沖洗它。是的,我認爲你也應該在Flush()之後做一個Response.End()。

讓我知道這是否有效,也許我可以運行一些我自己的測試。

+0

將BufferOutput更改爲true,並添加了End()。仍然沒有骰子。 – mickyjtwin 2009-05-20 04:05:50