Monday 22 June 2015

Upload and Delete File(s) using jQuery Multifile library in ASP.Net MVC

In this article I am going to demonstrate about multiple file upload and delete in asp.net mvc application by using jquery.multifile and jquery.form library.

You can easily upload and delete the single or multiple files in a single hit of server and no need to call server function in each and every upload or delete of files.

Download Source Code

Here I am taking one scenario as an example. Suppose we have Product information in a table and we want to upload multiple files for a single product.

 

1)      In this case we need two tables one is related to Product and other is related to Product Files. Let’s first create these two tables in database (sql script is given in project source code).

 

2)      Open Microsoft Visual Studio

3)      Create a new asp.net mvc empty application and choose razor view engine to implement this example.

4)      Download the following packages and include in your application.

a)      jQuery

b)      Bootstrap (optional)

c)       jquery.multifile

d)      jquery.form

5)      Add ADO.Net Entity Data Model for selecting the database tables (Product and Product File) in Models folder. It will generate .edmx in your application. This is called Database First Approach in Entity Framework.

6)      Now create a _Layout.cshtml (master page) in Views/Shared folder and add reference of these files.

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>@ViewBag.Title</title>

    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

    <link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />

    <link href="~/Content/style.css" rel="stylesheet" />

    <script src="~/Scripts/jquery-2.1.4.min.js"></script>

    <script src="~/Scripts/jquery.MultiFile.js"></script>

    <script src="~/Scripts/jquery.form.js"></script>

    <script src="~/Scripts/app.js"></script>

</head>

<body>

    <div class="container">

        @RenderBody()

    </div>

</body>

</html>

7)      Now create a ProductController in controller folder in order to render following views:

a)      Index (To display the list of the products)

b)      Create (To create a new product)

c)       Edit (To edit and update the existing product info)

d)      Details (To view to details of existing product)

e)      Delete (To Delete the existing Product)

 

8)      Add an Index action and a View (view available in project source code):

 public ActionResult Index()

        {

            using (ProductEntities db = new ProductEntities())

            {

                return View(db.Product.ToList());

            }

        }

9)      Add a Create action (GET & POST) and its View (view available in project source code):

 public ActionResult Create()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult Create(Product model, HttpPostedFileBase[] files)

        {

            bool success = false;

            string message = "";

 

            if (ModelState.IsValid)

            {

                using (ProductEntities db = new ProductEntities())

                {

                    db.Product.Add(model);

                    db.SaveChanges();

 

                    if (files != null && files.Length > 0)

                    {

                        foreach (var file in files)

                        {

                            if (file != null)

                            {

                                SaveFile(file, String.Format("~/content/product/{0}/", model.ProductID));

 

                                ProductFile fileObj = new ProductFile

                                {

                                    ProductID = model.ProductID,

                                    FileName = file.FileName

                                };

 

                                db.ProductFile.Add(fileObj);

                            }

                        }

                        db.SaveChanges();

                    }

 

                    success = true;

                    message = "Product saved successfully.";

                }

            }

            else

            {

                message = "Model State is not valid.";

            }

 

            return Json(new { success = success, message = message, callbackurl = Url.Action("Index") });

        }

10)   Same way you can add Edit, Detail and Delete actions and its view.

11)   There is two common functions (Save & Delete) for upload and delete of file is also available in Product controller.

        #region Save and Delete File Function

 

        private string SaveFile(HttpPostedFileBase httpfile, string directory, string filename = null)

        {

            if (httpfile != null && httpfile.ContentLength > 0)

            {

                string fileName = filename ?? httpfile.FileName;

 

                if (!System.IO.Directory.Exists(Server.MapPath(directory)))

                {

                    System.IO.Directory.CreateDirectory(Server.MapPath(directory));

                }

 

                string filePath = System.IO.Path.Combine(String.Format("{0}{1}", Server.MapPath(directory), fileName));

                httpfile.SaveAs(filePath);

                return String.Format("{0}{1}", directory, fileName);

            }

 

            return "";

        }

 

        private void DeleteFile(string filepath)

        {

            if (System.IO.File.Exists(Server.MapPath(filepath)))

            {

                System.IO.File.Delete(Server.MapPath(filepath));

            }

        }

 

        #endregion

 

If you run an application, the output should be something like below screenshot:


You can add, edit, view and delete the product and its files as well.

Edit Product screenshot is given below:

Thanks for reading this article. The missing action and view is available in project source. If you have any question and doubt you can freely ask me and do not forget to give your valuable comments.

Download Source Code

 

2 comments:

navya said...

Interesting article on ASP.NET MVC server side.

ASP.Net MVC Training

amehc said...

hello,

help with this, please

@(string.Join(" ; ", item.ProductFile.Select(m => m.FileName)))

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.