2014-10-02 33 views
0

我想在瀏覽器中顯示來自ftp的pdf文件。我找到了一些代碼,我試過了。 pdf在瀏覽器中顯示,但文件爲空。它具有所有頁面作爲原始文件,但沒有頁面上的內容。在ASP.net的FTP看起來空的瀏覽器從ftp

string filename = Request.QueryString["view"];  
FileInfo objFile = new FileInfo(filename); 

System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + objFile.Name)); 
request.Credentials = new NetworkCredential(Ftp_Login_Name,Ftp_Login_Password); 

System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse(); 
StreamReader reader = new StreamReader(responseStream); 

Stream responseStream = response.GetResponseStream(); 
Response.Clear(); 
Response.ClearHeaders(); 
Response.ClearContent(); 
Response.ContentEncoding = reader.CurrentEncoding; 
Response.ContentType = "application/pdf";    
Response.AddHeader("Content-Disposition", "inline; filename=" + Request.QueryString["name"]); 
Response.Write(reader.ReadToEnd()); 
Response.End(); 

如何在瀏覽器中正確顯示它? http://i.stack.imgur.com/8weMr.png

回答

0

Response.Write用於向客戶端發送文本。 PDF文件包含二進制內容,因此內容可能會被錯誤地轉換。使用Response.BinaryWrite代替。另外在你的代碼中,你並沒有發送這個文件。試試這個:

FileStream fs = File.OpenRead(filename); 

int length = (int)fs.Length; 
BinaryReader br = new BinaryReader(fs); 
byte[] buffer = br.ReadBytes(length); 

Response.Clear(); 
Response.ClearHeaders(); 
Response.ClearContent(); 
Response.ContentEncoding = reader.CurrentEncoding; 
Response.ContentType = "application/pdf";    
Response.AddHeader("Content-Disposition", "inline; filename=" + Request.QueryString["name"]); 
Response.BinaryWrite(buffer); 
+0

有了'Response.BinaryWrite'我應該使用的代碼,我不能用'reader.ReadToEnd()' – user4102037 2014-10-02 11:47:42

+0

什麼是'reader'對象? – DavidG 2014-10-02 11:49:07

+0

我在代碼中添加了它 – user4102037 2014-10-02 11:50:50

2

試試這個:

FileInfo objFile = new FileInfo(filename); 
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + filename)); 
request.Credentials = new NetworkCredential(Ftp_Login_Name, Ftp_Login_Password); 

FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 

Stream responseStream = response.GetResponseStream(); 
StreamReader reader = new StreamReader(responseStream); 

byte[] bytes = null; 
using (var memstream = new MemoryStream()) 
{ 
    reader.BaseStream.CopyTo(memstream); 
    bytes = memstream.ToArray(); 
} 

Response.Clear(); 
Response.ClearHeaders(); 
Response.ClearContent(); 
Response.Cache.SetCacheability(HttpCacheability.NoCache); 
Response.ContentType = "application/pdf"; 
Response.AddHeader("Content-Disposition", "inline; filename=" + objFile.Name); 
Response.BinaryWrite(bytes); 
Response.End(); 
+0

謝謝,這節省了我的頭痛......特別是爲了得到正確的字節數組我必須使用這個代碼:byte [] bytes = null; (memstream = new MemoryStream()) { bytes = memstream.ToArray(); } – tjones0808 2017-06-15 15:05:02