Tuesday, 25 October 2016

How to upload multiple image or files in asp.net mvc with Source Code



Introduction:
 Here I will explain how to upload multiple image in Asp.net MVC and save image path in database. This example is used for single and multiple file upload with help of FormColllection and HttpPostedFileBase.
User upload image and it save image in folder and path in database table with relevant id.
Description:

In Asp.net MVC we implement multiple file upload by fallowing Steps

Step1: Use fallowing query to Image table for saving image path
CREATE TABLE [dbo].[tbl_img] (
    [Sr_no]  INT            IDENTITY (1, 1) NOT NULL,
    [Image1] NVARCHAR (MAX) NULL,
    [Image2] NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_tbl_img] PRIMARY KEY CLUSTERED ([Sr_no] ASC)
);
Step2: Write fallowing Store Procedure for inserting Image path in tbl_img Table
Create proc SpAdd_Detail
@Image1 nvarchar(max),
@Image2 nvarchar(max)
as
begin
insert into tbl_img values(@Image1,@Image2)
end
Step3:  Add fallowing class in model and write fallowing properties in class
public class detail
    {
        public int Sr_no { get; set; }
        public string Image1 { get; set; }
        public string Image2 { get; set; }
    }
Step4:  Add fallowing class in Database_Access_Layer folder for communication with database

Step5:  Add fallowing funtion in db.cs class file
public class db
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);

        public void Add_Detail(detail dl)
        {
            SqlCommand com = new SqlCommand("SpAdd_Detail", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Image1", dl.Image1);
            com.Parameters.AddWithValue("@Image2", dl.Image2);
            con.Open();
            com.ExecuteNonQuery();
            con.Close();
        }

    }
Step6:  Add a new Rajor Index View file in View folder and fallowing code for upload image

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <form method="post" enctype="multipart/form-data">
            <table>
                <tr><td>Image1</td><td><input type="file" name="file" /></td></tr>
                <tr><td>Image2</td><td><input type="file" name="file" /></td></tr>
                <tr><td></td><td><input type="submit" value="submit" /></td></tr>
            </table>
        </form>
    </div>
    @{
        if (TempData["msg"]!=null)
        {
            <script>
                alert('@TempData["msg"]');

            </script>
        }
    }
</body>
</html>
Step7:  Write fallowing code in Home Controller file for inserting image path in database table and image into folder
public class HomeController : Controller
    {
        //
        // GET: /Home/
        Database_Acceess_Layer.db dblayer = new Database_Acceess_Layer.db();

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(FormCollection fc, IEnumerable<HttpPostedFileBase> file)
        {
            detail dl = new detail();

            string uplode = string.Empty; ;
            foreach (var item in file)
            {
                if (item==null)
                {
                    break;
                }
                string filename = Guid.NewGuid() + Path.GetExtension(item.FileName);
                string filepath = "../images/" + filename;
                item.SaveAs(Path.Combine(Server.MapPath("~/images"), filename));
                uplode += filepath + ":";
            }
            string[] patharray = uplode.Split(':');
            dl.Image1 = patharray[0].ToString();
            dl.Image2 = patharray[1].ToString();
            dblayer.Add_Detail(dl);
            TempData["msg"] = "Data Submitted Succesfully";
            return View();
        }

    }
Step8:  Now we will run the application and see the fallowing output
This is how to upload multiple image in asp.net mvc enviroment


Download Full Source Code Here:


Ads Inside Post