Uploading Image

So, last night a friends of mine raised a question on the Asp.Net MVC – Bangladesh group how he can upload images in ASP.Net MVC. Instantly, two answers appears in my mind as its solution. He can either use string or as byte[] to Upload, Save, Retrieve the image.
I also pointed the following code snipped :

Assuming you have stored your image in db as byte[] :

byte[] data = (byte[])ds.Tables[0].Rows[0][0];

MemoryStream strm = new MemoryStream();

strm.Write(data, 0, data.Length);

strm.Position = 0;

System.Drawing.Image img = System.Drawing.Image.FromStream(strm);

BitmapImage bi = new BitmapImage();

bi.BeginInit();

MemoryStream ms = new MemoryStream();

img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

ms.Seek(0, SeekOrigin.Begin);

bi.StreamSource = ms;

bi.EndInit();

imagebox.Source = bi;

Seeing this approach Alim Ul Karim vai pointed on the performance issue.
He left a very constructive suggestion, he said-

“If you are not using NOSQL this is not a good practice. To save the image use file system. Just upload the image to a file location and display it with the URL. and if you save a image in database it always converts it to binary which is very overkill for server where you could easily use the browser to work it for you. Simple things matters. “

So, keeping his suggestion in mind here it can be done –
For this demonstration at first I have created a model named “Picture.cs”. Inside which the following property is added :

public class Picture 
{
     Public HttpPostedFileBase File {get; set;}
}

Then you have to add a simple upload form in the view.

@using(Html.BeginForm(null, null, FormMethod.Post, new { enctype="multipart/form-data"}))
<table>
     <tr>
         <td> <input type="file" name="File" id="File" /> </td>
     </tr>

     <tr>
         <td> <input type="submit" name="submit" value="upload" /> </td>
     </tr>
</table>

Now in the desired controler page we have to post the content.

[HttpPost]
public ActionResult Index(Picture pic)
{
   //check for contents
   if(pic.File.ContentLength>0)
   {
        var fileName=Path.GetFileName(pic.File.FileName);
        var path=Path.Combine(Server.MapPath("~/Content/images"), fileName);
        pic.File.SaveAs(path);
   }
   return RedirectToAction("Index");
}

Run it! and You are good to GO! Retrieving images is fairly simple, so I am not demonstrating it here 🙂

If you want to upload multiple image then just change picture property/model as IEnumerable and add multiple in the form.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s