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
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.
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.
That’s it. Visual Studio will create the application structure.
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.
Step 2
In the next “Add Scaffold” wizard, select the “Web API 2 Controller- Empty” and click on “Add”
Step 3
Enter the controller name as “ImageServiceController”
Step 4
Add a “New Folder” named “Uploads” into the solution as shown below,
Step 5
Add the following code in the “ImageService” controller,
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Threading.Tasks;
- using System.Web.Hosting;
- using System.Web.Http;
-
- namespace ImagePool.Controllers
- {
- public class ImageServiceController : ApiController
- {
- #region Variables
- HttpResponseMessage response = new HttpResponseMessage();
- #endregion
-
- #region Public Methods
-
-
-
-
- [HttpPost, ActionName("UploadImage")]
- public async Task<HttpResponseMessage> UploadImage()
- {
-
- string sub = string.Empty;
- int ImageResult = 0;
-
- if (!Request.Content.IsMimeMultipartContent())
- {
- return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "This is not Mime Multipart Content");
- }
-
-
- string rootPath = HostingEnvironment.MapPath("~/Uploads/");
-
- var provider = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/Uploads/"));
- try
- {
-
- await Request.Content.ReadAsMultipartAsync(provider);
-
-
- string uploadedFileName = provider.FileData.First().Headers.ContentDisposition.FileName;
- if (uploadedFileName.Length == 0)
- {
- return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "Image file not found");
- }
-
- string uploadedFileNameWithBackSlash = uploadedFileName.LastIndexOf("\\").ToString();
-
- int position = uploadedFileName.LastIndexOf('\\');
-
-
- string fileNameext = string.Empty;
- var fileName = uploadedFileName.Substring(uploadedFileName.LastIndexOf(("\\")) + 1);
-
- int fileExtPos = fileName.LastIndexOf(".");
-
- if (fileExtPos >= 0)
- fileNameext = (fileName.Substring(fileExtPos, (fileName.Length - fileExtPos))).Replace("\"", "");
-
- sub = fileNameext;
-
- string[] extensionArray = { ".jpg,.png,.JPG,.PNG,.bmp,.gif" };
-
- List<string> extentions = extensionArray.FirstOrDefault().Split(',').Where(c => c.Equals(sub.ToLower())).ToList();
- if (extentions.Count == 0)
- {
- return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "file not supported");
- }
-
- String strFinalFileName = string.Empty;
- strFinalFileName = Guid.NewGuid().ToString().Trim().Replace(" ", "").Replace("-", "") + sub;
-
- String strDatabaseFilePath = string.Empty;
-
- rootPath = rootPath + "\\Images\\";
- strDatabaseFilePath = "/Uploads/" + "/Images/" + strFinalFileName;
-
- if (!System.IO.Directory.Exists(rootPath))
- {
- System.IO.Directory.CreateDirectory(rootPath);
- }
-
-
-
-
-
-
-
- var fullFilePath = provider.FileData.First().LocalFileName + sub;
- var copyToPath = rootPath + strFinalFileName;
- FileStream stream = File.OpenRead(provider.FileData.First().LocalFileName);
- byte[] fileBytes = new byte[stream.Length];
-
- stream.Read(fileBytes, 0, fileBytes.Length);
- double fileSizeKB = stream.Length / 1024;
-
- ImageResult = await NewCompressImageWithNewDimensions(stream, copyToPath, provider.FileData.First().Headers.ContentDisposition.Size.HasValue ? Convert.ToDouble(provider.FileData.First().Headers.ContentDisposition.Size) : 0);
- stream.Close();
-
-
- if (File.Exists(provider.FileData.First().LocalFileName))
- {
- File.Delete(provider.FileData.First().LocalFileName);
- }
-
- response = Request.CreateResponse(HttpStatusCode.OK, "Image Uploaded Successfully!");
- }
- catch (Exception ex)
- {
- response = Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
- }
- return response;
- }
- #endregion
-
- #region Private Methods
-
-
-
-
-
-
-
- private async Task<int> NewCompressImageWithNewDimensions(FileStream stream, string copyToPath, double fileSizeKB)
- {
- int result = 0;
- try
- {
- using (var image = Image.FromStream(stream))
- {
- double scaleFactor;
- if (fileSizeKB <= 900)
- {
- scaleFactor = 0.9;
- }
- else if (fileSizeKB <= 1500)
- {
- scaleFactor = 0.8;
- }
- else if (fileSizeKB <= 2000)
- {
- scaleFactor = 0.7;
- }
- else
- {
- scaleFactor = 0.3;
- }
- var newWidth = (int)(image.Width * scaleFactor);
- var newHeight = (int)(image.Height * scaleFactor);
- var CompressImage = new Bitmap(newWidth, newHeight);
- var CompressImageGraph = Graphics.FromImage(CompressImage);
- CompressImageGraph.CompositingQuality = CompositingQuality.HighQuality;
- CompressImageGraph.SmoothingMode = SmoothingMode.HighQuality;
- CompressImageGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
- var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
- CompressImageGraph.DrawImage(image, imageRectangle);
- CompressImage.Save(copyToPath, image.RawFormat);
- if (File.Exists(copyToPath))
- {
- result = 1;
- }
- else
- {
- result = 2;
- }
- }
- return result;
- }
- catch (Exception)
- {
- return result;
- }
- }
- #endregion
- }
- }
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”
Step 2
Select the Microsoft Azure App Service and click on “Publish”
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.
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”.
If publishing succeeds then the web app will launch on the browser.
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”.
Step 2
Now click on “Overview” and copy the “FTP Hostname”.
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
Step 4
Now go to the sites-> wwwroot. Create a new folder named “Uploads” as shown below,
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}
Image is saved on the Images folder inside the Upload folder.
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!!