Uploading Image To Server Using Web API 2.0

Here in this article I am going to explain how to upload image to the server using Web API. Web API is mainly used as a mediator between client and server. It exposes the server side data to the client like (Website, Android devices, iPhone device etc). The client can directly interact with the server using Web API. Web API exposes the server data in the form of JSON data.

Here, I will explain how to create a Web API to upload images to server.

The first step is to create a new project with a WEB API  template. Add an Empty controller to the project and name it "Upload" as below.

 

Name it "Upload Controller".
 
Create a new folder in your project root directory as "Userimage". 

 
 
Now create a method "PostUserImage" in Upload controller and write the following code. Here, I have shown the complete code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Threading.Tasks;  
  7. using System.Web;  
  8. using System.Web.Http;  
  9.   
  10. namespace CrystalReportIn_Webapi.Controllers  
  11. {  
  12.      [RoutePrefix("api/Upload")]  
  13.     public class UploadController : ApiController  
  14.     {  
  15.   
  16.         [Route("user/PostUserImage")]  
  17.          [AllowAnonymous]  
  18.         public async Task<HttpResponseMessage> PostUserImage()  
  19.         {  
  20.             Dictionary<stringobject> dict = new Dictionary<stringobject>();  
  21.             try  
  22.             {  
  23.   
  24.                 var httpRequest = HttpContext.Current.Request;  
  25.   
  26.                 foreach (string file in httpRequest.Files)  
  27.                 {  
  28.                     HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);  
  29.   
  30.                     var postedFile = httpRequest.Files[file];  
  31.                     if (postedFile != null && postedFile.ContentLength > 0)  
  32.                     {  
  33.   
  34.                         int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB  
  35.   
  36.                         IList<string> AllowedFileExtensions = new List<string> { ".jpg"".gif"".png" };  
  37.                         var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));  
  38.                         var extension = ext.ToLower();  
  39.                         if (!AllowedFileExtensions.Contains(extension))  
  40.                         {  
  41.   
  42.                             var message = string.Format("Please Upload image of type .jpg,.gif,.png.");  
  43.   
  44.                             dict.Add("error", message);  
  45.                             return Request.CreateResponse(HttpStatusCode.BadRequest, dict);  
  46.                         }  
  47.                         else if (postedFile.ContentLength > MaxContentLength)  
  48.                         {  
  49.   
  50.                             var message = string.Format("Please Upload a file upto 1 mb.");  
  51.   
  52.                             dict.Add("error", message);  
  53.                             return Request.CreateResponse(HttpStatusCode.BadRequest, dict);  
  54.                         }  
  55.                         else  
  56.                         {  
  57.   
  58.                              
  59.   
  60.                             var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + postedFile.FileName + extension);  
  61.                             
  62.                             postedFile.SaveAs(filePath);  
  63.   
  64.                         }  
  65.                     }  
  66.   
  67.                     var message1 = string.Format("Image Updated Successfully.");  
  68.                     return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;  
  69.                 }  
  70.                 var res = string.Format("Please Upload a image.");  
  71.                 dict.Add("error", res);  
  72.                 return Request.CreateResponse(HttpStatusCode.NotFound, dict);  
  73.             }  
  74.             catch (Exception ex)  
  75.             {  
  76.                 var res = string.Format("some Message");  
  77.                 dict.Add("error", res);  
  78.                 return Request.CreateResponse(HttpStatusCode.NotFound, dict);  
  79.             }  
  80.         }  
  81.     }  
  82. }  
Now add "Advance REST client" to check the following Web API as below.

Search" Advance Rest Client for Chrome" in Google  and download.

 

Click add to Chrome so that it will appear in your browser app.

 
 
Click on the ARC to test the Web API as below.

 

Now click the Files and  browse to choose an image as in the following.

 

After choosing click the send button.

 
The Status 200:OK  and the message shows that the image has uploaded, if we want to check it in the following folder it will appear in the folder as in the following.
 
 

So in this way we can upload image to server using Web API.
 
Read more articles on Web API:

Up Next
    Ebook Download
    View all
    Learn
    View all