Upload Server-side Code

The following ASP.NET MVC code shows an example controller that can be used for handling upload form submits, as well as asynchronous file upload and removals:

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace Shield.Examples.Controllers
{
    public class UploadController : Controller
    {
        [HttpPost]
        [ActionName("submit")]
        public ActionResult Submit(IEnumerable files)
        {
            // TODO: perform authorization

            return View("Upload/SubmitSummary", GetFilesInfo(files));
        }

        [HttpPost]
        [ActionName("save")]
        public ActionResult Save(IEnumerable files)
        {
            // TODO: perform authorization

            if (files != null)
            {
                foreach (var file in files)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        // extract only the filename
                        var fileName = Path.GetFileName(file.FileName);

                        // store the file inside ~/App_Data/uploads folder
                        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                        file.SaveAs(path);
                    }
                }
            }

            return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
        }

        [HttpPost]
        [ActionName("remove")]
        public ActionResult Remove(string[] fileNames)
        {
            // TODO: perform authorization

            if (fileNames != null)
            {
                foreach (var fullName in fileNames)
                {
                    // extract the filename
                    var fileName = Path.GetFileName(fullName);

                    // get the physical path
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);

                    // delete the file if existing
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                }
            }

            return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
        }

        private IEnumerable GetFilesInfo(IEnumerable files)
        {
            return files
                .Where(q => q != null)
                .Select(q => string.Format("{0} ({1} bytes)", q.FileName, q.ContentLength));
        }
    }
}