How to Insert and Read a Pdf file, into a SQL Server from a ASP.Net Web Form Using C#?
I am Using the following code:
To Insert:
MemoryStream msp= new MemoryStream();
FileStream strem = new FileStream("myUpload", FileMode.Create);
Object pf1 = FileUpload1.PostedFile.ToString();
BinaryFormatter bf=new BinaryFormatter();
bf.Serialize(strem, pf1);
long sz = strem.Length;
msp.Close();
cmd.CommandText = "INSERT INTO myUpload (ok) VALUES (@Up)";
cmd.Parameters.AddWithValue("Up", msp.ToArray());
To Read:
{
Byte[] mypdf = getpdf();
Response.Clear();
Response.BufferOutput = true;
Response.ContentType = "images/jpeg";
Response.BinaryWrite(mypdf);
}
private Byte[] getpdf()
{
SqlConnection cn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd1 = new SqlCommand();
cn1.Open();
cmd1.Connection = cn1;
cmd1.CommandText = "SELECT ok FROM myUpload where(Id=24)";
FileStream fs2 = new FileStream("myUpload", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs2);
Byte[] data = br.ReadBytes((int)fs2.Length);
br.Close();
fs2.Close();
cn1.Close();
return data;
}