Storing and Retrieving Images in SQL Server
I typically use the File System for storing images, that doesn't work so well when using a web farm. Below is an example of storing the image information into SQL server and then retrieving and rendering image back on the page.
The datatype for the image column I am using is the varbinary(max). For this example I am allowing the upload of an image so I limit both the size and file extension type.
Upload Action
The datatype for the image column I am using is the varbinary(max). For this example I am allowing the upload of an image so I limit both the size and file extension type.
Upload Action
[HttpPost] public ActionResult Upload(HttpPostedFileBase file, DataModel.MyClass imginfo) { if (ModelState.IsValid) { if (file == null) { } else if (file.ContentLength > 0) { int MaxContentLength = 1024 * 1024 * 3; //3 MB - Could put this in a config string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".JPG", ".jpeg", ".JPEG", ".GIF", ".PNG" }; if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.')))) { ViewBag.Message = "Your file must be JPG, GIF or PNG"; } else if (file.ContentLength > MaxContentLength) { ViewBag.Message = "Your file is too large, maximum allowed size is 3 meg"; } else { //imginfo is the dataclass I passed in imginfo.imageContentType = file.ContentType; //This is a temp save var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Assets/"), imginfo.imageName); file.SaveAs(path); imginfo.imagePath = "Assets/" + imginfo.imageName; imginfo.imageFile = ImageTypeOptions.GetPhoto(path); //adding straight into my table dt.TableName.Add(imginfo); dt.SaveChanges(); //deleting the temp image //since file system deletions can be buggy we are going to throw into a static method //with a try catch just so it doesn't stop us TryToDelete(path); ViewBag.Message = "File uploaded successfully"; } } } return RedirectToAction("Final", new { id = imginfo.AccountCode, dppID = imginfo.dppID, message = "Successfully Uploaded image" }); } Static TrytoDelete method private static bool TryToDelete(string f) { try { System.IO.File.Delete(f); return true; } catch (IOException) { return false; } } Static method to convert the image to a format to insert into database public static byte[] GetPhoto(string filePath) { FileStream stream = new FileStream( filePath, FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(stream); byte[] photo = reader.ReadBytes((int)stream.Length); reader.Close(); stream.Close(); return photo; } Then to display on the page just use it like this we are passing in the ID of the row (AssetID): <img src="@Url.Action( "DisplayImage", "Fran", new { id = item.AssetID })" width="50" height="50" /> And the action that we are calling public ActionResult DisplayImage(int id) { var img = db.TableName.Find(id); byte[] imageData = img.imageFile; var contType = img.imageContentType; return new FileStreamResult(new System.IO.MemoryStream(imageData), contType); } |
Comments