articles

Home / DeveloperSection / Articles / File Upload and Download in MVC.

File Upload and Download in MVC.

Anonymous User 3681 02-Aug-2018

File Upload and Download in MVC.

1). Add a Button on IndexPage for open a modal popup for FileUploadControl like given this image.

2). And add a partial view for define modal popup’s design here, using bootstrap for it.

@model  MvcAppFirst.Customer


@{
    ViewBag.Title = "_UploadedFiles";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>_UploadedFiles</h2>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<link href="~/Content/jQuery.FileUpload/css/jquery.fileupload.css" rel="stylesheet" />
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<style>
    .bg {
        background-color: darkgray;
    }

    .BG {
        background-color: Gainsboro;
    }

    #loadingImg {
        display: none;
    }
</style>


<div class="modal-content" style="width: 800px !important;">
    @using (Html.BeginForm("SaveFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.HiddenFor(m => m.CustomerID, new { @Value = TempData["ID"] })
        <div class="modal-header">

            <h5 class="modal-title" id="exampleModalLabel" align="center">Choose Your File</h5>

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <div class="container">
                <div class="col-md-12">
                    <div class="form-area">
                        <div class="container" align="center">
                            <input type="file" multiple="multiple" name="file" class="BG" />
                            <button type="submit" value="Upload Files" class="btn btn-info">Upload File</button>
                            <br />
                        </div>

                    </div>
                </div>

            </div>

        </div>
    }
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    </div>
    }
</div>

File Upload and Download in MVC.

3). Create an ActionMethod for uploading files. And attach a folder to the SolutionExplorer to keep the uploaded files safe.

//----------For Image/File Upload------//


        [HttpGet]
        public ActionResult SaveFile(int customerID)
        {
            TempData["ID"] = customerID;
            return PartialView("_UploadedFiles");
        }

        [HttpPost]
        public ActionResult SaveFile(Customer model, HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
                try
                {
                    string path = Path.Combine(Server.MapPath("~/SavedFiles"), Path.GetFileName(file.FileName));
                    file.SaveAs(path);
                    bool success = false;
                    var Customer = AP.Customers.Where(x => x.CustomerID == model.CustomerID).FirstOrDefault();
                    if (Customer != null)
                    {
                        success = AP.INSERTorUPDATE_CUSTOMER(Customer.CustomerID, Customer.Name, Customer.Mobileno, Customer.Address, Customer.Birthdate, DateTime.Now, Customer.EmailID, path) == 1 ? true : false;
                        AP.SaveChanges();
                    }
                    ViewBag.Message = "File uploaded successfully";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }
            return RedirectToAction("Index");
        }

File Upload and Download in MVC.

4). Add a Download button (or Link button) in IndexView Page for download saved files.

For this action, we can define only the ActionMethod for download.

//---------------Download Files-------------//


        public ActionResult Downloads(int customerID)
        {
            Customer model = AP.Customers.FirstOrDefault(x => x.CustomerID == customerID);

            if (model != null)
            {
                if (System.IO.File.Exists(Server.MapPath(resolveVirtual(model.UploadFiles))))
                {
                    string fileName = Path.GetFileName(resolveVirtual(model.UploadFiles));
                    byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath(resolveVirtual(model.UploadFiles)).ToString());
                    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
                }
            }

            return null;
        }

        public static string resolveVirtual(string physicalPath)
        {
            string url = physicalPath.Substring(System.Web.HttpContext.Current.Server.MapPath("~").Length).Replace('\\', '/').Insert(0, "~/");
            return (url);
        }

5). Work on IndexViewPage.

@using (Html.BeginForm("DownloadFile", "Controller", FormMethod.Get)){}

File Upload and Download in MVC.



Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By