Saving Image To Database Using MVC
Saving an image to a database is not hard to do as you might think. I developed a sample Asp.net MVC application demonstrating this. You may get the complete code from my github.
Below is the Model I have. The important thing here is byte[] which is the one that is saved in the database while the HttpPostedFileBase is the data posted from the View.
[Table("Car")]
public class Car
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)
, Key()]
public int CarId { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
//[Required]
[StringLength(100)]
public string Type { get; set; }
public byte[] ImageFile { get; set; }
[StringLength(200)]
public string ImageContentType { get; set; }
[StringLength(200)]
public string ImageFileName { get; set; }
List<Maintenance> MaintenanceSchedule { get; set; }
[NotMapped]
[Required]
public HttpPostedFileBase FileAttach { get; set; }
}
This is the View control code in its simple form. You can see the complete code of the control from this link.
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype =
"multipart/form-data" }))
{
<div class="form-group">
@Html.LabelFor(model => model.ImageFile, htmlAttributes:
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.FileAttach, new { type = "file",
accept = "image/jpeg,image/jpg,image/png",
placeholder = Html.DisplayNameFor(m => m.FileAttach),
@class = "form-control" })
@Html.ValidationMessageFor(model => model.FileAttach, "",
new {@class = "text-danger" })
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create"
class="btn btn-default" />
</div>
</div>
</div>
}
Here is the code in the Controller to save in the database using Entity Framework.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include =
"CarId,Name,Type,ImageFile,FileAttach")] Car car)
{
UpdateFileDetails(car);
if (ModelState.IsValid)
{
db.Car.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
private void UpdateFileDetails(Car car)
{
HttpPostedFileBase postedFile = car.FileAttach;
if (postedFile != null)
{
byte[] bytes;
using (BinaryReader br = new BinaryReader
(postedFile.InputStream))
{
bytes = br.ReadBytes(postedFile.ContentLength);
}
car.ImageFileName = Path.GetFileName(postedFile.FileName);
car.ImageContentType = postedFile.ContentType;
car.ImageFile = bytes;
}
}
As you can see from the code above, with a few lines of code, you will be able to save an image to a database. Hope this helps anyone who is looking to implement this in their project!