Creating controller for File Upload

Kailash Chandra Behera | Thursday, March 30, 2017

Introduction

This blog shares code snippet for creating a simple MVC WEB API Controller for uploading files.

Code Snippet

 using System;  
 using System.Net.Http;  
 using System.Web.Http;  
 using System.IO;  
 namespace FileUploadDemonstrator  
 {  
   public class FileUploaderController : ApiController  
   {  
           private string _filePath;  
           private int _noOfFileUploaded;  
           private System.Web.HttpFileCollection _files;  
           public FileUploaderController()  
           {  
                this.FilePath=System.Web.Hosting.HostingEnvironment.MapPath(ConfigurationManager.AppSettings["FilePath"]);  
                this.=_noOfFileUploaded;  
           }  
     [HttpPost()]  
     public int Upload()  
     {  
       this._files = System.Web.HttpContext.Current.Request.Files;  
       for (int ind = 0; iCnt <= this._files.Count - 1; ind++)  
       {  
         System.Web.HttpPostedFile _file = this._files[ind];  
         if (_file.ContentLength > 0)  
         {  
           try{  
             _file.SaveAs(this.FilePath + Path.GetFileName(_file.FileName));  
             this._noOfFileUploaded++;  
           }  
                          catch(Exception ex)  
                          {  
                          }  
         }  
       }  
       return this._noOfFileUploaded;  
     }  
   }  
 }  

Related Articles

  1. Import Excel in C#
  2. Export DataTable To Excel in C#
  3. Import XML into SQL Table
  4. Export Table Data into XML in SQL
  5. Export to Excel in MVC
  6. Export HTML Table to Excel Using JavaScript
  7. Validating Excel Sheet in C#
  8. Reading Excel file in AngularJS

Summary

Hope this article may helpful to you, happy coding and enjo.......y.

Thanks