2009-04-20 174 views
1

我遇到了將PDF文件寫入瀏覽器的問題。其他MIME類型工作正常。 PDF文件被損壞。Response.WriteFile PDF文件 - 損壞的文件

FileInfo file = new FileInfo(Path.Combine(_module.FileDir, _file.FilePath)); 
Response.ClearContent(); 
Response.ClearHeaders(); 
Response.ContentType = _file.ContentType; 
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Regex.Replace(_file.FilePath, "\\s", "-")); 
Response.AppendHeader("Content-Length", file.Length.ToString()); 
try 
{ 
    Response.WriteFile(file.FullName); 
    Response.Flush(); 
    Response.Close(); 
} 
catch 
{ 
    Response.ClearContent(); 
} 

回答

1

我的問題是HTTP模塊。我正在應用白色空間過濾器

HttpApplication app = sender as HttpApplication; 
    if (app != null && app.Request.RawUrl.Contains(".aspx")) 
    { 
     app.Response.Filter = new WhitespaceFilter(app.Response.Filter); 
    } 
0

對於這種情況,一個Response.Redirect的應該工作一樣好:

FileInfo file = new FileInfo(Path.Combine(_module.FileDir, _file.FilePath)); 
Response.Redirect(file.FullName); 
+1

我假設OP不希望有直接下載的內容,可能是通過某種認證機制或其他方式。 Response.Redirect會公開URL,而OP的技術(和我的回覆中的Microsoft)將允許內容來自用戶可以在Web服務器上訪問的IIS上下文的任何位置,從而有可能更好地保護它。 (是的,我是磨合判罰之王。) – 2009-04-20 21:17:36

+0

很好的建議。我將重定向請求以避免HTTP模塊啓動 – user81740 2009-04-20 21:27:49

0
  1. 你確保你得到正確的MIME類型?
  2. 您是否試圖強制用戶下載或流出PDF數據?
  3. 您是否在任何地方執行Response.End()調用以確保不會發送額外的數據(頭文件和PDF二進制文件之外)?

我在想這是#3,可能是你的問題在這裏。 Microsoft's Knowledge Base提供了這個代碼,基本上,你看起來在做什麼。

//Set the appropriate ContentType. 
Response.ContentType = "Application/pdf"; 
//Get the physical path to the file. 
string FilePath = MapPath("acrobat.pdf"); 
//Write the file directly to the HTTP content output stream. 
Response.WriteFile(FilePath); 
Response.End(); 
1

你需要這三個語句:

Response.Flush(); Response.Close(); Response.End();

最後一個是最重要的。