code_junkie

Upload images to SQL Server 2005 using ASP.Net MVC

Nov 13th, 2011
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. MyClass obj = new MyClass();
  2. obj.Name = Request["name"]; // other properties
  3. obj.Alt = Request["altText"];
  4.  
  5. HttpPostedFile file = Request.Files[0];
  6. if (file != null)
  7. {
  8. obj.Image image = new byte[file.ContentLength];
  9. file.Read(obj.Image,0,file.ContentLength];
  10. }
  11.  
  12. using (DataContext context = new DataContext())
  13. {
  14. context.InsertOnSubmit( obj );
  15. context.SubmitChanges();
  16. }
  17.  
  18. String b64;
  19. using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
  20. {
  21. this.pic.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  22. Byte[] bytes = ms.ToArray();
  23. b64 = Convert.ToBase64String(bytes);
  24. }
  25. using (SqlConnection conn = new SqlConnection(ConnectionString))
  26. {
  27. using (SqlCommand cmd = new SqlCommand("UPDATE [settings] SET [value] = @val WHERE [id] = 2", conn))
  28. {
  29. conn.Open();
  30. cmd.Parameters.Add(new SqlParameter("@val", b64));
  31. cmd.ExecuteNonQuery();
  32. conn.Close();
  33. }
  34. }
  35.  
  36. SqlConnection conn = new SqlConnection("<your connection string>");
  37. conn.Open();
  38.  
  39. SqlCommand cmd = new SqlCommand("TestProc", conn);
  40. cmd.CommandType = CommandType.StoredProcedure;
  41.  
  42. SqlParameter param = new SqlParameter("@data", SqlDbType.Image);
  43. param.Value = System.IO.File.ReadAllBytes("any_file.jpg");
  44. cmd.Parameters.Add(param);
  45.  
  46. cmd.ExecuteNonQuery();
Add Comment
Please, Sign In to add comment