I'm new to asp.net mvc and now im having trouble adding and retrieving images from database. I think the adding is fine, its when reading back the images that's the problem. It always show chrome broken image icon.
Here's my database table configuration:
CREATE TABLE [dbo].[Image](
[id] [int] IDENTITY(1,1) NOT NULL,
[img] [varbinary](max) NULL,
CONSTRAINT [PK_Image] PRIMARY KEY CLUSTERED
(
[id] ASC
)
Here's my controller:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
public ActionResult Show(int id)
{
var imageData = db.Images.Find(id).img;
return File(imageData, "image/jpg");
}
public ActionResult Create()
{
Image image = new Image();
return View(image);
}
[HttpPost]
public ActionResult Create(Image image, HttpPostedFileBase file1)
{
if(file1 != null)
{
image.img = new byte[file1.ContentLength];
file1.InputStream.Read(image.img, 0, file1.ContentLength);
}
db.Images.Add(image);
db.SaveChanges();
return View(image);
}
Here's my detail view:
@model Project1.Models.Image
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Image</h4>
<hr />
<img src='@Url.Action( "Show", "Image", new { id = Model.id } )' />
</div>
and my create view:
@model Project1.Models.Image
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Images", FormMethod.Post, new { enctype="multipart/form-data"}))
{
<div class="form-horizontal">
<h4>Image</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.img, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="file1" name="file1"/>
</div>
</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>
}