Uploading Files To Web Server (IIS) Using HttpPostedFileHelper Library In Asp.Net MVC

HTTP Posted File Helper V.1.0.2   Nugget Link

This is a light weight library that helps in the posting of files to IIS Web Server by providing a helper class FileHElper.cs which contains overloaded method ProcessFile() and ProcessFIleAsync() that reduces the boilerplate in posting files.

Installing.. 

Type the command below  in Visual Studio Nuget Package Manager Console to install the library.
 
  1. PM> Install-Package HttpPostedFileHelper  

 Usage

Processing Single Files (Basic Usage)

  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult UploadFile(HttpPostedFileBase file) {  
  4.     //Instanciate the Filehelper class to create a Filehelper Object  
  5.     FileHelper filehelper = new FileHelper();  
  6.     filehelper.ProcessFile(file, "/MyTargetLocation");  
  7.     return view();  
  8. }   

Processing Multiple Files

This makes a provision for multiple files being uploaded to the Server with an overridden method for processing an IEnumerable of files (HttpPostedFileBase Collection).

  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult UploadFile(Model model, IEnumerable < HttpPostedFileBase > file) {  
  4.     FileHelper filehelper = new FileHelper();  
  5.     // ProcessFile returns count of files processed  
  6.     int postedfiles = filehelper.ProcessFile(file, "/MyTargetLocation");  
  7.     if (postedfiles > 0) {  
  8.         //files were written successfully  
  9.     }  
  10.     return View("Home");  
  11. }   

Asynchronous File Processing

Processing files can be done asynchronously. This allows large files to be processed in the background thread freeing the main thread.

  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public async Task < ActionResult > UploadFile(Model model, IEnumerable < HttpPostedFileBase > file) {  
  4.     FileHelper filehelper = new FileHelper();  
  5.     await filehelper.ProcessFileAsync(file, "/MyTargetLocation");  
  6.     //you can do some other work while awaiting  
  7.     return View("Home");  
  8. }  

Reject File Extensions During Upload

You can specify the file types to be rejected during an upload by supplying a string of the file extensions.

  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public async Task < ActionResult > UploadFile(Model model, IEnumerable < HttpPostedFileBase > file) {  
  4.     FileHelper filehelper = new FileHelper();  
  5.     string reject = ".jpeg,.png,.svg";  
  6.     int postedfiles = await filehelper.ProcessFileAsync(file, "/MyTargetLocation", reject); //you can do some other work while awaiting  
  7.     if (postedfiles > 0) {  
  8.         //files were written successfully  
  9.     }  
  10.     return View("Home");  
  11. }  

Thanks for reading this blog. I hope it will help someone.