2014-01-08 43 views
0

C#代碼:使用C#從oracle數據庫顯示pdf文件(pdf路徑存儲在數據庫中)?

HyperLink1.NavigateUrl = "Pdfhandler.ashx?empid=" + TextBox8.Text; 

Pdfhandler.ashx代碼:

{ 

     MemoryStream memoryStream = new MemoryStream(); 

     string sql = "SELECT pdfpath FROM pdfstore WHERE empl_code = " + id + ""; 

     OracleCommand cmd = new OracleCommand(sql, connection); 
     //cmd.Parameters.AddWithValue("@id", id); 
     connection.Open(); 

     OracleDataReader reader = cmd.ExecuteReader(); 
     reader.Read(); 
     if (reader.HasRows) 
     { 
      //byte[] file = Encoding.ASCII.GetBytes("imgpath"); 
      //byte[] file = Encoding.UTF8.GetBytes("imgpath"); 
      //Get Image Data 
      //byte[] file = (byte[])reader["imgpath"]; 
      byte[] file = File.ReadAllBytes(reader["pdfpath"].ToString()); 

      reader.Close(); 
      connection.Close(); 
      memoryStream.Write(file, 0, file.Length); 
      context.Response.Buffer = true; 
      context.Response.BinaryWrite(file); 
      memoryStream.Dispose(); 
     } 
     else 
     { 

     } 

當我運行代碼我可以能夠通過輸入僱員代碼來顯示的PDF爲一個僱員,但如果我進入另一個僱員代碼在文本框中,特定員工的pdf沒有被顯示。任何人都可以解決這個問題嗎?

+0

如果pdfpath只是一個字符串,爲什麼使用ReadAllBytes? – Steve

+0

那我應該用什麼來代替? – user3168680

+0

memorystream有問題嗎?我應該清除它嗎?如果是這樣如何?因爲我可以在某段時間後顯示PDF。 – user3168680

回答

1

你可以嘗試這樣的事情

if (reader.HasRows) 
{ 
    context.Response.Clear(); 
    context.Response.ContentType = "application/pdf"; 
    context.Response.TransmitFile(reader["pdfpath"].ToString()); //the path must be actual physical path of the file 
    contest.Response.End(); 
} 
else 
{ 
    context.Response.Clear(); 
    context.Response.ContentType = "text/plain"; 
    context.Response.Write("No file found"); 
    contest.Response.End(); 
} 
+0

非常感謝你的工作。但在Internet Explorer中,我需要刷新頁面才能打開PDF。如何解決這個問題? – user3168680

+0

你可以嘗試設置'HyperLink1.Target =「_blank」;'。這將在新選項卡中打開PDF。那麼你將不需要刷新。 – th1rdey3

+0

我已經給出了這個。但問題仍然存在,在Firefox中它的工作正常。 – user3168680

相關問題