Creating controller for File Upload in Web API


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;  
     }  
   }  
 }  

Summary

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

Thanks
Kailash Chandra Behera


No comments:

Post a Comment