How to upload an image with other form data in ASP.Net MVC?

In this blog, I will write about How to upload an image with other form data in ASP.Net MVC 5. You may read my other articles on MVC.

Sometimes, we require to collect image/photo with other form inputs. For eg – A resume form. This form will have normal inputs as well as image upload to save candidates profile photo.

Here, I will demonstrate to save image in MVC step by step. You can use this code to upload/save any type of file like pdf, doc, Docx, Xls, etc.

Step1 – Create a table with fields like name, email, phone, image

Step2 – Write Stored Procedure to insert data into the table.

CREATE PROCEDURE Add_Update_Select_SP]
       — Add the parameters for the stored procedure here
@name nvarchar(300)=null,
@email nvarchar(300)=null,
@phone nvarchar(300)=null,
@image nvarchar(500)=null,
@Exists int = null OUTPUT
AS
BEGIN
       — SET NOCOUNT ON added to prevent extra result sets from
       — interfering with SELECT statements.
       SET NOCOUNT ON;
        
    — Insert statements for procedure here
        
      
        
      
       IF EXISTS(SELECT id
                        FROM Customer
                        WHERE email = @email OR phone = @phone)
                                           BEGIN
                                           SET @Exists = 1
                                           END
                                           ELSE
                                           BEGIN
       INSERT INTO Customer(name,email,phone ,imagepath) values(@name,@email,@phone,@image)
       SET @Exists = 0
       END
      
       RETURN @Exists
        
END

Step3 – Create a new MVC project in Visual Studio. I have used Visual Studio 2017.
Create a new model UserModel. Add properties which will be used in form.

public class UserModel
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        ///<summary>
        /// Gets or sets Name.
        ///</summary>
        public string Email { get; set; }
        ///<summary>
        /// Gets or sets Gender.
        ///</summary>
       
        public string Phone { get; set; }
        public string ImagePath { get; set; }
        public HttpPostedFile ImageFile { get; set; }
        //public byte[] File { get; set; }
    }

Step 4 – Design your UI based on the requirement. You may notice a little difference in Html.BeginForm. There is an extra parameter – new { enctype = “multipart/form-data” }
It requires when we use file upload in our form.

@model WebApplication1.UserModel
@{
    ViewBag.Title = “Our Customer”;
}
@using (Html.BeginForm(“User”, “Home”, FormMethod.Post, new { enctype = “multipart/form-data” }))
{
<div class=”container”>
        <div class=”row”>
<div class=”col-md-4 well well-sm”>
                <fieldset>
                    <legend>Fill below form:</legend>
                    <div class=”form-group”>
                        <label for=”name”>
                            Name<i>*</i>
                        </label>
                        <div class=”input-group”>
                            <span class=”input-group-addon”>
                                <span class=”glyphicon glyphicon-user”></span>
                            </span>
                            @Html.TextBoxFor(m => m.FullName, new { placeholder = “Enter Name”, @class = “form-control”, required = “required” })
                        </div>
                    </div>
                    <div class=”form-group”>
                        <label for=”email”>
                            Email Address
                        </label>
                        <div class=”input-group”>
                            <span class=”input-group-addon”>
                                <span class=”glyphicon glyphicon-envelope”></span>
                            </span>
@Html.TextBoxFor(m => m.Email, new { type = “email”, placeholder = “Enter Email”, @class = “form-control” })
                        </div>
                    </div>
                    <div class=”form-group”>
                        <label for=”email”>
                            Phone </label>
                        <div class=”input-group”>
                            <span class=”input-group-addon”>
                                <span class=”glyphicon glyphicon-phone”></span>
                            </span>
@Html.TextBoxFor(m => m.Phone, new { placeholder = “Enter Phone”, @class = “form-control” })                           
                        </div>
                    </div>
                    <div class=”form-group”>
                        Upload Image<i>*</i>
                        <div class=”col-md-10″>
                            <input type=”file” name=”ImageFile” required />
                        </div>
                    </div>
                    <div>
                        <input type=”submit” class=”btn btn-primary pull-right” value=”Submit” />
                    </div>
                </fieldset>
                @if (@ViewBag.Result != “” || @ViewBag.Result != null)
                {
                    <div class=”” style=”color:blue;font-size:20px; font-weight:bold; role=”alert”>
                        @ViewBag.Result
                    </div>
                }
            </div>
</div>
    </div>
}

Step5 – Write Action method of type HttpPost.
You may notice there are 2 parameters in the Action method.
One is UserModel type to collect inputs data from the form, another parameter is of type HttpPostedFileBase to get file information which is being uploaded.

Note: Parameter name for HttpPostedFileBase and name value for file type control in view should be same. Otherwise, you will receive null value in the 2nd parameter.
I have used ImageFile in Action method parameter and in the View file

        [HttpPost]
        public ActionResult User(UserModel usermodel, HttpPostedFileBase ImageFile)
        {
            int result = 5;
            try
            {                               
                if (ImageFile.ContentLength > 0)
                {
                    string fileExt = Path.GetExtension(ImageFile.FileName);
                    var fileName = Path.GetFileName(Guid.NewGuid() + ImageFile.FileName);
                    string filePath = “Uploads/” + fileName;
                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“dbcon”].ConnectionString);
                    SqlCommand cmd = new SqlCommand(“Add_Update_Select_SP”, con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue(“@name”, usermodel.FullName);
                    cmd.Parameters.AddWithValue(“@email”, usermodel.Email);
                    cmd.Parameters.AddWithValue(“@phone”, usermodel.Phone);
                    cmd.Parameters.AddWithValue(“@image”, filePath);
                    cmd.Parameters.AddWithValue(“@action”, 2);
                    cmd.Parameters.Add(“@Exists”, SqlDbType.Int);
                    cmd.Parameters[“@Exists”].Direction = ParameterDirection.Output;
                   
                    con.Open();
                    cmd.ExecuteNonQuery();
                    result = (int)cmd.Parameters[“@Exists”].Value;
                    if (result == 0)
                    {
                        var path = Path.Combine(Server.MapPath(“~/Uploads “), fileName);
                        ImageFile.SaveAs(path);
                        ViewBag.Result = “Data Saved Successfully”;
                    }
                    else
                    {
                        ViewBag.Result = “Record Already Exist”;
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Result = “Sorry, There is some error”;
            }
            return View(usermodel);
        }

In the above code, I have checked file length and then used ADO.Net to save the information into a table, once everything is ok then have uploaded file at the desired location.

Once you fille the form and hit submit button you can see File details while debugging the application.

Hope you like this blog.
Please share this blog on social media and give your feedback in the comment box below.
You may like other blogs –

Interview Questions and Answers Series –

MVC Interview Questions and Answers
Web API interview questions and answers

Leave a Comment

RSS
YouTube
YouTube
Instagram