How to upload multiple file in Asp.NET MVC 3

by adeyinka oluwaseun 22. April 2012 00:16

This post will show how to upload multiple file in Asp.Net MVC 3 without encountering any issue. The UI for the page would look like this : 

 

The view that create the UI above : 

@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
 
        if (ViewBag.Success != null)
        {
            <span><strong>@ViewBag.Success</strong></span>
        }
 
        if (ViewBag.OperationError != null)
        {
           <span><strong>@ViewBag.OperationError</strong></span>
        }
 
        if (ViewBag.NoFile != null)
        {
              <span><strong>@ViewBag.NoFile</strong></span>
        }    
         
        <br />  
        <input type="file" class="fileInput" name="file" />
        <br />
        <input type="file" class="fileInput" name="file" />
        <br />
        <input type="file" class="fileInput" name="file" />
        <br />
        <input type="file" class="fileInput" name="file" />  
        <br />
        <input type="submit" value="Upload" />
 
    }
</p>

 The Controller Class for the View , the HomeController is the Controller for this view : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MultiplyUploadInaspNetMvc.Utility;
 
namespace MultiplyUploadInaspNetMvc.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
 
        [HttpPost]
        public ActionResult Index(List<HttpPostedFileBase> file)
        {
            if (file.IsHttpPostedFileNull()) {
             // IsHttpPostedFileNull() is an extension method i created
             // to check if the fileupload controls has file in order to
             // prevent errors incase no file was uploaded by the user.
                try                          
                {
                    bool result = Upload.FileUploader(file);
                    if (result)
                    {
                        ViewBag.Success = "File successfully uploaded !!!";
                    }
 
                    return View();
                }
                catch (Exception ex)
                {
                    ViewBag.OperationError = ex.Message;
                    return View();
                }
            }
 
            ViewBag.NoFile = "No file was uploaded !!!";
            return View();
        }
 
        public ActionResult About()
        {
            return View();
        }
 
    }
}
 

 

 

This is the code for the extension method that checks whether a file was uploaded by the user : 

Note : if this is not done , if no file was uploaded at all then we have exceptions but this check helps to prevent such errors :

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace MultiplyUploadInaspNetMvc.Utility
{
    public static class ListExtension
    {
        public static bool IsHttpPostedFileNull(this List<HttpPostedFileBase> file)
        {
            return file.Any(postedFile => postedFile != null);
        }
    }
}

Finally , we have the class responsible for uploading the files into the specified directory , this class also contains a method that uses regular expression to check the file extensions on the server-side. : 

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
 
namespace MultiplyUploadInaspNetMvc.Utility
{
    public class Upload
    {
        private static string _path = string.Empty;
     
        // take in : HttpPostedFileBase , return bool , note : file is the HttpPostedFileBase variable that is pass in to the func.
        public static Func<List<HttpPostedFileBase>, bool> FileUploader = file =>
        {
            try
            {
                foreach (HttpPostedFileBase currentFile in file)
                {
                    if (currentFile != null) // check to see if the fileupload has file in it
                    {
                        bool answer = CheckFileExtensions(Path.GetFileName(currentFile.FileName));
                        if (answer == false)
                        {
                            throw new Exception(
                                "Wrong File Format , Only picture formats such as .jpeg/.jpg/.png are allowed !!!");
                        }
                        else
                        {
                            var generateNewFileName = Path.GetFileName(currentFile.FileName);
                            _path = Path.Combine(HttpContext.Current.Server.MapPath("~/Upload/" + generateNewFileName));
                        }
                       
                        currentFile.SaveAs(_path);
                    }
                }
                return true;
            }
 
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        };
       
        // method to check for file to be uploaded extension , it must be an image in this case
        private static bool CheckFileExtensions(string fileName)
        {
            var regex = new Regex(@".*(|\.[Pp][Nn][Gg]|\[Jj][Pp][Ee][Gg])");
            return regex.IsMatch(fileName);
        }
    }
}

 

The full source code is also available for download :  MultiplyUploadInaspNetMvc.rar (460.48 kb)

How to fix up ASPState Login Error

by Adeyinka Oluwaseun Doyin 14. April 2012 08:35

just go to the web config section of your web project , Add this under the System.Web Section sessionState mode =”InProc” cookieless =”AutoDetect”

Tags:

 

Page List

RecentComments

None

Month List

Category list

None

Month List

Go to Top