Upload Image/Display Image in Asp.Net MVC

One of the main issue for beginners is how to upload image and display it (after upload) in asp.net mvc. So, this article demonstrate the basics of uploading image and display it after uploading.

So, first thing first, we have to write alittle html to create upload input and a button to submit the data to the server in a view like this;

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{  
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 
}

Next thing is to when this form is posted to the server, we should handle the posted image in our controller. So, let's write a code in a controller (in this case "Home" and action result "FileUpload". you can see it in defined in BeginForm).

public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (file != null)
        {
            string pic = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(
                                   Server.MapPath("~/images/profile"), pic); 
            // file is uploaded
            file.SaveAs(path);

            // save the image path path to the database or you can send image 
            // directly to database
            // in-case if you want to store byte[] ie. for DB
            using (MemoryStream ms = new MemoryStream()) 
            {
                 file.InputStream.CopyTo(ms);
                 byte[] array = ms.GetBuffer();
            }

        }
        // after successfully uploading redirect the user
        return RedirectToAction("actionname", "controller name");
    }

That's all we have to do. If you are still not satisfied, you can find my ansewr at stackoverflow where i have even more helpful links for e.g Uploading file using jQuery plugins. Here is the link for stackoverflow;

http://stackoverflow.com/questions/16255882/how-to-upload-image-display-image-in-asp-net-mvc-4/16256106


3.0 2

Existing reviews

display
Please ask how to display the saved image in next view.
Thank you
From: Guest | Date: 7/20/2015 2:44 PM
Was this review helpful? Yes / No (11/23)
why its not working
code its good but not suited for freshers
From: Guest | Date: 9/9/2015 10:59 AM
Was this review helpful? Yes / No (11/15)


Write your own review
Bad Excellent