How to save image in database in MVC3?

Posted by Nishant_Mittal under Others on 11/27/2012 | Points: 10 | Views : 5916 | Status : [Member] | Replies : 0
HI,

I need a to save the uploaded image in database in byte[ ] format. I am using image datatype to save the image. Byte datatype also can be used.



model class for image i have used:-

public class ImageSave
{
[Key]
public int ID
{ get; set; }


public string ImageName
{ get; set; }


[MaxLength]
public byte[] ImageUpload
{ get; set; }

}


View i have used:-

@model MvcPractice.Models.ImageSave

@{
ViewBag.Title = "Create";
}

<h2>Save Image</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Student</legend>

<div class="editor-label">
@Html.LabelFor(model => model.ImageName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ImageName)
@Html.ValidationMessageFor(model => model.ImageName)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.ImageUpload)
</div>
<div class="editor-field">
<input type="file" name="file" /> @Html.EditorFor(model => model.ImageUpload)
@Html.ValidationMessageFor(model => model.ImageUpload)
</div>

<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}


Controller code which is not working:-

[HttpPost]
public ActionResult Create(ImageSave imageSave)
{
try
{


// TODO: Add insert logic here
if (ModelState.IsValid)
{
db.ImagesSaves.Add(imageSave);
db.SaveChanges();
return RedirectToAction("Create");
}
return View(imageSave);

}
catch
{
return View(imageSave);
}
}


need controller that work with the model given above. any other code or suggestions will also welcome.

Thanks
Nishant Mittal




Responses

(No response found.)

Login to post response