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

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!!