使用C#从oracle数据库显示pdf文件(pdf路径存储在数据库中)?

时间:2014-01-08 11:50:12

标签: c# asp.net oracle pdf handler

C#代码:

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。任何人都可以帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分: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();
}