我正在使用asp.net应用程序,它在页面上显示从数据库中检索到的pdf文件。我正面临着pdf文件未在页面中显示的问题
有了这个,我附上了我试过的代码:
con.Open();
SqlCommand cmd = new SqlCommand("select Pdf from SavePdf where IC='" + id +
"'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] fileData = (byte[])dr.GetValue(0);
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.BinaryWrite(fileData);
Response.Flush();
Response.End();
}
dr.Close();
}
答案 0 :(得分:2)
使用此代码
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int id = int.Parse(Request.QueryString["id"]);
Display(id);
}
}
private void Display(int id)
{
DataSet ds = GetData("select * from tblFiles where Id=@Id", id);
Byte[] bytes = (Byte[])ds.Tables[0].Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
private DataSet GetData(string query, int id)
{
string conString = ConfigurationManager.ConnectionStrings["constr_files"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
cmd.Parameters.Add("@Id", id);
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
答案 1 :(得分:1)
我尝试了你的代码,它对我来说很完美。
protected void ShowPdfButton_Click(object sender, EventArgs e)
{
byte[] fileData = GetPdfBytes();
Response.Buffer = true;
Response.Charset = "";
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.BinaryWrite(fileData);
Response.Flush();
Response.End();
}
private byte[] GetPdfBytes()
{
string pdfFileFullName = @"C:\Reports\Test.pdf";
//TODO: you can fetch the bytes from database as well and return. i have used pdf file.
return System.IO.File.ReadAllBytes(pdfFileFullName);
}