Uploading Image Using Microsoft Azure APP Service

Hey folks, today we’ll learn to upload an image to a web server using ASP.NET Web API which will be hosted on Microsoft Azure. We can also say that, we’ll use Microsoft Azure App Service to upload the image.

In this article, we’ll create an ASP.Net Web Application using Web API Project Template and host the web application as Azure App Service in the Microsoft Azure. So, let’s create an application with the following procedure:

  • Creating Web Application
  • Adding Controller
  • Hosting API to Azure
  • Azure APP Deployment
  • Using Azure APP Service

Prerequisites

These are the following prerequisites before creating the application:

Note

I am using Visual Studio 2017 to create the application.

Creating Web Application

In this section, we’ll create the ASP.NET Web Application using Web API project template. Start with the following steps:

Step 1

Open Visual Studio and click on File-> New->Project

Azure

Step 2

In the next wizard, select the “Web” from the left pane and select the “ASP.Net Web Application” and enter the name as “ImagePool”. Click on OK.

Azure

Step 3

In the next “One ASP.Net” wizard, select the “Web API” Project Template to create the ASP.Net Web API application. Authentication for the application will remain as “No Authentication”. If you want to use ASP.Net Identity for registration purpose then you can select “Individual Authentication”. Click on OK.

Azure

That’s it. Visual Studio will create the application structure.

Azure

Build the application and now let’s move to the next section.

Adding Controller

In this section, we’ll add a Web API controller and create a method to upload the image into the server. Follow the procedure below:

Step 1

In Solution Explorer, Right click on the Controllers and go to Add-> Controller.

Azure

Step 2

In the next “Add Scaffold” wizard, select the “Web API 2 Controller- Empty” and click on “Add”

Azure

Step 3

Enter the controller name as “ImageServiceController”

Azure

Step 4

Add a “New Folder” named “Uploads” into the solution as shown below,

Azure

Step 5

Add the following code in the “ImageService” controller, 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Drawing.Drawing2D;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Threading.Tasks;  
  10. using System.Web.Hosting;  
  11. using System.Web.Http;  
  12.   
  13. namespace ImagePool.Controllers  
  14. {  
  15.     public class ImageServiceController : ApiController  
  16.     {  
  17.         #region Variables  
  18.         HttpResponseMessage response = new HttpResponseMessage();  
  19.         #endregion  
  20.  
  21.         #region Public Methods  
  22.         /// <summary>  
  23.         /// This method is created to upload the image.  
  24.         /// </summary>  
  25.         /// <returns></returns>  
  26.         [HttpPost, ActionName("UploadImage")]  
  27.         public async Task<HttpResponseMessage> UploadImage()  
  28.         {  
  29.   
  30.             string sub = string.Empty;  
  31.             int ImageResult = 0;  
  32.   
  33.             if (!Request.Content.IsMimeMultipartContent())  
  34.             {  
  35.                 return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "This is not Mime Multipart Content");  
  36.             }  
  37.   
  38.             //This is the static path for user images  
  39.             string rootPath = HostingEnvironment.MapPath("~/Uploads/");  
  40.             //get the path where content of MIME multipart body parts are written to  
  41.             var provider = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/Uploads/"));  
  42.             try  
  43.             {  
  44.                 //read multi part data  
  45.                 await Request.Content.ReadAsMultipartAsync(provider);  
  46.   
  47.                 //get the file name from returned data  
  48.                 string uploadedFileName = provider.FileData.First().Headers.ContentDisposition.FileName;  
  49.                 if (uploadedFileName.Length == 0)  
  50.                 {  
  51.                     return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "Image file not found");  
  52.                 }  
  53.   
  54.                 string uploadedFileNameWithBackSlash = uploadedFileName.LastIndexOf("\\").ToString();  
  55.   
  56.                 int position = uploadedFileName.LastIndexOf('\\');  
  57.   
  58.   
  59.                 string fileNameext = string.Empty;  
  60.                 var fileName = uploadedFileName.Substring(uploadedFileName.LastIndexOf(("\\")) + 1);  
  61.   
  62.                 int fileExtPos = fileName.LastIndexOf(".");  
  63.   
  64.                 if (fileExtPos >= 0)  
  65.                     fileNameext = (fileName.Substring(fileExtPos, (fileName.Length - fileExtPos))).Replace("\"""");  
  66.   
  67.                 sub = fileNameext;  
  68.                 //check file is image type  
  69.                 string[] extensionArray = { ".jpg,.png,.JPG,.PNG,.bmp,.gif" };  
  70.   
  71.                 List<string> extentions = extensionArray.FirstOrDefault().Split(',').Where(c => c.Equals(sub.ToLower())).ToList();  
  72.                 if (extentions.Count == 0)  
  73.                 {  
  74.                     return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "file not supported");  
  75.                 }  
  76.   
  77.                 String strFinalFileName = string.Empty;  
  78.                 strFinalFileName = Guid.NewGuid().ToString().Trim().Replace(" """).Replace("-""") + sub;  
  79.   
  80.                 String strDatabaseFilePath = string.Empty;  
  81.   
  82.                 rootPath = rootPath + "\\Images\\";  
  83.                 strDatabaseFilePath = "/Uploads/" + "/Images/" + strFinalFileName;  
  84.   
  85.                 if (!System.IO.Directory.Exists(rootPath))  
  86.                 {  
  87.                     System.IO.Directory.CreateDirectory(rootPath);  
  88.                 }  
  89.   
  90.                 //do stuff to save the file path into the datbase  
  91.                 //{  
  92.                     // save the file path to the database  
  93.                 //}  
  94.   
  95.                 // After saving image compress it and save image to the directory.  
  96.                 var fullFilePath = provider.FileData.First().LocalFileName + sub;  
  97.                 var copyToPath = rootPath + strFinalFileName;  
  98.                 FileStream stream = File.OpenRead(provider.FileData.First().LocalFileName);  
  99.                 byte[] fileBytes = new byte[stream.Length];  
  100.   
  101.                 stream.Read(fileBytes, 0, fileBytes.Length);  
  102.                 double fileSizeKB = stream.Length / 1024;  
  103.   
  104.                 ImageResult = await NewCompressImageWithNewDimensions(stream, copyToPath, provider.FileData.First().Headers.ContentDisposition.Size.HasValue ? Convert.ToDouble(provider.FileData.First().Headers.ContentDisposition.Size) : 0);  
  105.                 stream.Close();  
  106.   
  107.                 //delete temp file  
  108.                 if (File.Exists(provider.FileData.First().LocalFileName))  
  109.                 {  
  110.                     File.Delete(provider.FileData.First().LocalFileName);  
  111.                 }  
  112.   
  113.                 response = Request.CreateResponse(HttpStatusCode.OK, "Image Uploaded Successfully!");  
  114.             }  
  115.             catch (Exception ex)  
  116.             {  
  117.                 response = Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);  
  118.             }  
  119.             return response;  
  120.         }  
  121.         #endregion  
  122.  
  123.         #region Private Methods  
  124.         /// <summary>  
  125.         /// This method is created to compress the image.  
  126.         /// </summary>  
  127.         /// <param name="stream">file stream</param>  
  128.         /// <param name="copyToPath">target path</param>  
  129.         /// <param name="fileSizeKB">file size</param>  
  130.         /// <returns></returns>  
  131.         private async Task<int> NewCompressImageWithNewDimensions(FileStream stream, string copyToPath, double fileSizeKB)  
  132.         {  
  133.             int result = 0;  
  134.             try  
  135.             {  
  136.                 using (var image = Image.FromStream(stream))  
  137.                 {  
  138.                     double scaleFactor;  
  139.                     if (fileSizeKB <= 900)  
  140.                     {  
  141.                         scaleFactor = 0.9;  
  142.                     }  
  143.                     else if (fileSizeKB <= 1500)  
  144.                     {  
  145.                         scaleFactor = 0.8;  
  146.                     }  
  147.                     else if (fileSizeKB <= 2000)  
  148.                     {  
  149.                         scaleFactor = 0.7;  
  150.                     }  
  151.                     else  
  152.                     {  
  153.                         scaleFactor = 0.3;  
  154.                     }  
  155.                     var newWidth = (int)(image.Width * scaleFactor);  
  156.                     var newHeight = (int)(image.Height * scaleFactor);  
  157.                     var CompressImage = new Bitmap(newWidth, newHeight);  
  158.                     var CompressImageGraph = Graphics.FromImage(CompressImage);  
  159.                     CompressImageGraph.CompositingQuality = CompositingQuality.HighQuality;  
  160.                     CompressImageGraph.SmoothingMode = SmoothingMode.HighQuality;  
  161.                     CompressImageGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  162.                     var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);  
  163.                     CompressImageGraph.DrawImage(image, imageRectangle);  
  164.                     CompressImage.Save(copyToPath, image.RawFormat);  
  165.                     if (File.Exists(copyToPath))  
  166.                     {  
  167.                         result = 1;  
  168.                     }  
  169.                     else  
  170.                     {  
  171.                         result = 2;  
  172.                     }  
  173.                 }  
  174.                 return result;  
  175.             }  
  176.             catch (Exception)  
  177.             {  
  178.                 return result;  
  179.             }  
  180.         }  
  181.         #endregion  
  182.     }  
  183. }   

In the above code , I’ve uploaded the image file to the application hosted environment . You can also save the file path (if needed) to the database and compress the image after saving the path into the database.

Step 5

Build the application.

Hosting API to Azure

In this section, we’ll host the application to Microsoft Azure. After publishing we can use the Azure API to upload the image. Let me show you how to do it using the following steps,

Step 1

In the Solution Explorer, right click on the application and click on “Publish”

Azure

Step 2

Select the Microsoft Azure App Service and click on “Publish”

Azure

Note

If you already created a web app to Microsoft Azure which can be used as the Microsoft Azure App Service, then  you can select the option “Select Existing”.

Step 3

In the next “Create App Service” wizard , enter the web app name for hosting.

Azure

Note

I have created my resource group to Azure. You can leave that option as to the default or you can create new resource group.

Step 4

When you click on “Create”, it’ll publish the app to the Microsoft Azure. You can see the progress on the “Output Window”.

Azure

If publishing succeeds then the web app will launch on the browser.

Azure

Azure App Deployment

In this section, we’ll set up the deployment process of the Azure App. We have added a folder “Uploads” on the application but it’ll not be available on the Azure app for saving the images. So, we’ll setup it on this section. Follow the steps below:

Step 1

Open the app in the Microsoft Azure Portal

Step 2

Click on the “Deployment Credentials” in the “Deployment” section. Define the FTP name and password. Click on “Save”.

Azure

Step 2

Now click on “Overview” and copy the “FTP Hostname”.

Azure

Step 3

Now open “File Explorer” and enter the “FTP Hostname” in the Address Bar. It will ask for the “UserName” and “Password”. Enter the “FTP UserName” and Password

Azure

Step 4

Now go to the sites-> wwwroot. Create a new folder named “Uploads” as shown below,

Azure

This folder is created so that all images will be saved into this.

Using Azure App Service

The Azure App is successfully hosted. So, now we can call the azure app url and upload the image to the server. Follow the steps:

Step 1

Open the “Postman” or “Fiddler” to execute the API.

Step 2

Enter the web app url and pass the image in the Form Data as shown below:

Call URL will be as :

{Azure App Url}/api/{controller name}/{method name}

Azure

Image is saved on the Images folder inside the Upload folder.

Azure

That’s it.

Source Code

For the source code, you can go to the following url:

https://github.com/thenimitjoshi/ImagePoolAPI

Summary

This article described to create a Microsoft Azure App Service and App deployment and how we can upload files to the hosting environment using Azure App Service. Thanks for reading the article. Happy Coding!!


Similar Articles