I am working on a blog site. The user can 'browse' through a FileUpload control and select multiple images to be uploaded along with their post. Each post has a unique Message ID in the DB. I have figured out how to insert all of the uploaded files into the DB under one message ID like this: (I insert them as data type 'image')
try
{
conn.Open();
SqlCommand cmdInsert = new SqlCommand("INSERT INTO BlogMessages (Title, Message, Date, Author, IPAddress) VALUES (@Title, @Message, @Date, @Author, @IPAddress)", conn);
cmdInsert.Parameters.AddWithValue("@Title", tbTitle.Text.Trim());
cmdInsert.Parameters.AddWithValue("@Message", tbMessage.Text.Trim());
cmdInsert.Parameters.AddWithValue("@Date", DateTime.Now);
cmdInsert.Parameters.AddWithValue("@Author", tbAuthor.Text.Trim());
cmdInsert.Parameters.AddWithValue("@IPAddress", ip);
cmdInsert.ExecuteNonQuery();
if (imageUpload.HasFiles)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
HttpPostedFile file;
SqlCommand maxMessId = new SqlCommand("SELECT Max(MessageID) FROM BlogMessages", conn);
lastMessageID = Convert.ToInt32(maxMessId.ExecuteScalar());
foreach (var uploadedFile in imageUpload.PostedFiles)
{
file = uploadedFile;
MemoryStream ms = new MemoryStream();
file.InputStream.CopyTo(ms);
byte[] byts = ms.ToArray();
ms.Dispose();
SqlCommand cmdInsertImage = new SqlCommand("INSERT INTO BlogImages(Image, MessageID) VALUES (@Image, @MessageID)", conn);
cmdInsertImage.Parameters.AddWithValue("@Image", SqlDbType.Image).Value = byts;
cmdInsertImage.Parameters.AddWithValue("@MessageID", lastMessageID);
cmdInsertImage.ExecuteNonQuery();
byts = null;
cmdInsertImage = null;
}
}
However, I am having trouble dynamically retrieving the images for display in my ImageHandler. It seems that I am able to get all of the images under a specific MessageID and insert them into a dataset, but after that is what I am looking for guidance on, and I have not been able to come up with a working solution through research thus far. Here is the relevant code inside public void Process Request of ImageHandler.ashx.cs:
try
{
int messageid = Convert.ToInt32(context.Request.QueryString["mid"]);
SqlDataAdapter sda = new SqlDataAdapter("SELECT Image from BlogImages WHERE Image IS NOT NULL AND MessageID=" + messageid, conn);
System.Data.DataSet data = new DataSet();
sda.Fill(data);
if (data !=null)
{
byte[] result = (byte[])data.Tables[0].Rows[0]["ImageContent"];
result.Initialize();
context.Response.ContentType = data.Tables[0].Rows[0]["ImageExt"].ToString();
context.Response.BinaryWrite(result);
}
else
{
context.Response.WriteFile("No Image");
}
}
Thank you!