Friday, 11 January 2013

Creating Asynchrous File Uploader in MVC3 with Kendo UI



Asynchronous Upload
View: UploadFile.cshtml
@using Kendo.Mvc.UI
@{
    ViewBag.Title = "UploadFile";
    //Layout = "~/Views/Shared/_PlainLayout.cshtml";
}

<h2>Upload File</h2>

<div style="width:45%">
    @(Html.Kendo().Upload()
          .Name("files")
          .Async(a => a
                          .Save("SaveFiles", "Upload")
                          .Remove("RemoveFiles", "Upload")
                          .AutoUpload(true)
          )
          )
</div>

<script type="text/javascript">
    $(document).ready(function () {
       
        $(".k-dropzone").css("height","100px");

    });
</script>
<script src="~/Scripts/kendo.all.min.js"></script>
<link href="~/Content/kendo.common.min.css" rel="stylesheet" />

Controller:
  public class UploadController : Controller
    {
        public ActionResult UploadFile()
        {
            return View();
        }

        public ActionResult SaveFiles(IEnumerable<HttpPostedFileBase> files)
        {
            if (files != null)
            {
                foreach (var file in files)
                {
                   
                    var fileName = Path.GetFileName(file.FileName);
                    var physicalPath = Path.Combine(Server.MapPath("~/Content/UploadFile"), fileName);

                    // Saving the File
                    file.SaveAs(physicalPath);
                }
            }

            // Return an empty string to signify success
            return Content("");
        }

        public ActionResult RemoveFiles(string[] fileNames)
        {
           if (fileNames != null)
            {
                foreach (var fullName in fileNames)
                {
                    var fileName = Path.GetFileName(fullName);
                    var physicalPath = Path.Combine(Server.MapPath("~/Content/UploadFile"), fileName);

                   

                    if (System.IO.File.Exists(physicalPath))
                    {
                        // Deleting the File from the Location
                         System.IO.File.Delete(physicalPath);
                    }
                }
            }
            return Content("");
        }
    }

Calling to the File Upload Control
$('#Searchwindow').kendoWindow({
        title: "Upload File",
        content: "/Upload/UploadFile",
        height: "400px",
        width: "600px",
        iframe: true,
        visible: false
    }).data('kendoWindow').center();
<div id="grid">
            <div id="Searchwindow"></div>
</div>

No comments:

Post a Comment