Note that there are some explanatory texts on larger screens.

plurals
  1. POAsp.Net Adding Images to SQL Table...What am I doing wrong?
    text
    copied!<p>I have done this previously but in a different way. I am trying to get the code below to work. If I do not cast 'OriginalPhoto' or 'Thumbnail' an error occurs. Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. I don't understand why it asking to cast. However if I do cast it, the images add to the database just fine in a binary data format. When trying to view the images, i get the error 'Unable to display the given data'. I have inserted both byte[] into a table using a SqlDataAdapter and that works. I want to use this method though, what am I doing wrong? </p> <p>PROFILEGALLERY TABLE CONTAINS:</p> <p>UserId nvarchar(50)<br> Title nvarchar(10)<br> OriginalImage varbinary(max)<br> ThumbImage varbinary(max) </p> <pre><code>protected void AddPhotoToDatabase() { byte[] OriginalPhoto = GetImage(); byte[] Thumbnail = GenerateThumbnail(); string Title = FileUpload1.FileName.ToString(); string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES ('" + User.Identity.Name + "', '" + Title + "', CAST('" + OriginalPhoto + "'AS VARBINARY(MAX)), CAST('" + Thumbnail + "'AS VARBINARY(MAX)))"; string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(strCon); SqlCommand comm = new SqlCommand(sql, conn); conn.Open(); comm.ExecuteNonQuery(); conn.Close(); } protected byte[] GetImage() { byte[] photo = new byte[FileUpload1.PostedFile.ContentLength]; FileUpload1.PostedFile.InputStream.Read(photo, 0, photo.Length); return photo; } protected byte[] GenerateThumbnail() { System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream); double thumbwidth = 0; double thumbheight = 0; double imgsz = 150.0; if (imgsz / image.Width &lt; imgsz / image.Height) { thumbwidth = image.Width * (imgsz / image.Width); thumbheight = image.Height * (imgsz / image.Width); } else { thumbwidth = image.Width * (imgsz / image.Height); thumbheight = image.Height * (imgsz / image.Height); } System.Drawing.Image thumb = image.GetThumbnailImage((int)thumbwidth, (int)thumbheight, delegate() { return false; }, (IntPtr)0); MemoryStream ms = new MemoryStream(); thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return ms.ToArray(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload