Click here to Skip to main content
16,012,843 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Friends,
In my project i need to store the image file as a binary data into the database.I have create one "column" in mysql database and declared as "varbinary".
And i have tried this following code.
HttpPostedFile file = FileUpload1.PostedFile;
            Stream stream = file.InputStream;
            BinaryReader br = new BinaryReader(stream);
            byte[] byt = br.ReadBytes((int)stream.Length);         
 cmd = new MySqlCommand("Insert into db_image (Image) values ('" + byt + "')", con);
            cmd.ExecuteNonQuery();

Then i seen my database the data is storing as "System.byte" . How to Retrieve it.
Is it Correct method .Please help me.
Posted

C#
// Read the file and convert it to Byte Array
string filePath = Server.MapPath("APP_DATA/TestDoc.docx");
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();

//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900