0

Recently I started learning ASP.NET MVC 4 and I am struggling with how to add an image/bitmap object to a Model that I have and let the user pick an image from his desktop to upload, so I could save it to my database for displaying it later on my website.

In my training website i am doing a guitar selling website , I got a model that has Id , title , brand and price. All i did was creating a index page to show all the GutiarDataContext from the database and a create page , but i want to make an option for the creation to choose an image and save it to the database and off course displaying it in the Index view.

I already went through some answers on the internet and here but I couldn't really understand what they were trying to explain there, so if someone could show me an example and explanation on how it works, that would be awesome!

Thanks :)

ToastMaster
  • 135
  • 1
  • 9

2 Answers2

0

For Storing images in database :

In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-

Controller :

[HttpPost]
public ActionResult Upload(UploadViewModel model, HttpPostedFileBase file)
{
 if (file != null)
 {
    int byteCount = file.ContentLength;   <---Your file Size or Length
    .............
    .............
 }
}

View :

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  <input type="file" name="file" />
  <input type="submit" value="OK" />
}

For displaying images from database(i m taking a hypothetical example here)

<img height="80" width="140" class="imgThumb" src="@Url.Action("LoadImg", "Image", new { id = m.ImgId })" alt="Loading..." />

public ActionResult LoadImg(int id)
{
byte[] image = null;
tblImage img = en.tblImages.FirstOrDefault(i => i.ImgId == id);
image = (byte[])img.ImgSrc;
return File(image, "image/png");
}
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
  • Awesome , but how do you implement the model image object? – ToastMaster Aug 04 '14 at 07:40
  • @IdoM...i will recommend you to read model image object from here ... http://www.dotnet-tricks.com/Tutorial/mvc/aX9D090113-File-upload-with-strongly-typed-view-and-model-validation.html.......best tutorial for strongly typed file upload..Thankzzz.... – Kartikeya Khosla Aug 04 '14 at 07:47
  • I pretty much got it now and the website you gave me is great , thanks a lot Exception :) – ToastMaster Aug 04 '14 at 07:50
0

Controler Code

    public static byte[] GetImageFromUpload()
    {
        HttpPostedFileBase postedFile = null;

        if (HttpContext.Current.Request != null && HttpContext.Current.Request.Files.Count > 0)
            postedFile = new HttpPostedFileWrapper(HttpContext.Current.Request.Files["imageUpload"]);

        if (postedFile == null || postedFile.FileName == string.Empty) return null;

        using (Image img = Image.FromStream(postedFile.InputStream))
        {
            var file = new byte[postedFile.InputStream.Length];

            var reader = new BinaryReader(postedFile.InputStream);
            postedFile.InputStream.Seek(0, SeekOrigin.Begin);

            file = reader.ReadBytes((int)postedFile.InputStream.Length);

            return file;
        }
    }

LoadEmployeeImageToObject() method can use to add the imege to Byte arry and parse it to server using session

    public static void LoadEmployeeImageToObject(byte[] photo , int employeeId)
    {
        if (HttpContext.Current.Request != null)
        {
            byte[] uploadedImageFromFileControl = GetImageFromUpload();
            bool removeImage = HttpContext.Current.Request["removeImage"] == "on";

            if (HttpContext.Current.Session["AjaxPhoto"] != null)
            {
                photo = (byte[])HttpContext.Current.Session["AjaxPhoto"];
            }
            else if (uploadedImageFromFileControl != null) photo = uploadedImageFromFileControl;
            else if (employeeId != 0) //load image from db
            {
                photo = photo;
            }
        }
    }

if you are using this code no need to create database column for save image on database.just put a column for save picture id.using below jS script you can save image on server file system.(File path)

function uploadFile() {
    var fd = new FormData();
    fd.append("imageUpload", document.getElementById('imageUpload').files[0]);
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    xhr.open("POST", "/HumanResource/Employee/AjaxImageUpload");//controller path
    xhr.responseType = 'blob';
    xhr.send(fd);
    $('#divUploadStatus').show();
}

this JS method can bind with your patial view.chtml file like this

<div id="divUploadPanel">
    <label>
         Upload New Image:</label>
     <input type="file" id="imageUpload" name="imageUpload" onchange=" uploadFile(); " /><br />

this is the code for parent chtml file

    <div class="control-group">
        <label class="control-label" >Photo</label>
        <div class="controls">
            @Html.Partial("_EditorImagePanel", Model)
        </div>
    </div>

Hope this will help to you.thanks :)

CodeMind
  • 616
  • 1
  • 7
  • 19