C# -Saving a base64 string as an image into a folder on server in .Net Web API


In this article, we will learn how to save a base64 string as an image into a folder on the server using C# and Web API. I’m working on a mobile app and I have a requirement to upload images via an Android app. So, I decided to take the image as Base64 from the API and save it to the server folder. After completing my task, I decided to share the code.

Now, let’s start.

  • Create an Empty WebApi
  • Create an API controller.
  • Create a folder where we need to save the Images.

Now Copy Paste The Below

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;

namespace DemoWebApi.Controllers
{
    public class ImageModel
    {
    public string base64Image { get; set; }
    public string imagename { get; set; }
    }
    public class FileUploadController : ApiController
    {
    // POST: api/FileUpload
    public JsonResult<object> Post([FromBody]ImageModel Image)
        {
    try
            {
    string ImgName = Image.imagename;
    if (!string.IsNullOrEmpty(Image.base64Image))
                {
    //Image image = Base64ToImage(Image.base64Image);
                    String path = HttpContext.Current.Server.MapPath("~/Filestorage"); //Path
    //Check if directory exist
    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
    //If directory doesn't exist then Create it 
                    }
    string imageName = ImgName + ".jpg";
    //set the image path
    string imgPath = Path.Combine(path, imageName);
    if (Image.base64Image.Contains("data:image"))
                    {
    //Need To remove some header information at the beginning if image data contains
    //ImageDataUrl = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD....";
    //Otherwise, this will give an error.
    //Remove everything in front of the DataUrl and including the first comma.
    //ImageDataUrl = "9j/4AAQSkZJRgABAQAAAQABAAD...
                        Image.base64Image = Image.base64Image.Substring(Image.base64Image.LastIndexOf(',') + 1);
    // removing extra header information 
                    }
    byte[] imageBytes = Convert.FromBase64String(Image.base64Image);
                    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
                    ms.Write(imageBytes, 0, imageBytes.Length);
                    System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
                    image.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
    return Json((object)new
                    {
                        status = "Success",
                    });
                }
    return Json((object)new
                {
                    status = "Content not found",
                });
            }
    catch(Exception ex)
            {
    return Json((object)new
                {
                    Status = false,
                    Message = "Something went wrong with wrong.Please try after some time",
                });
            }
           
        }
    }
}

Now Let’s do testing above code is working or not. Open Postman and Hit the API.

Let’s Check server folder,you will able to see your image

 ASP.NET Web API controller named FileUploadController,  contains a class ImageModel that defines two properties: base64Image for storing a base64 encoded image string and imagename for storing the name of the image.

Within the FileUploadController class, there is a Post method that handles HTTP POST requests. It takes an ImageModel object as input from the request body. Inside the method, it first extracts the image name from the ImageModel object.

Then, it checks if the base64Image property is not null or empty. If it's not empty, the method proceeds to convert the base64 string into an image and save it to the server. It first determines the server path where the image will be saved. If the directory doesn't exist, it creates it.

Afterwards, it prepares the image path by combining the server path and the image name. If the base64 string contains header information, it removes it to get the raw image data. 

Then, it converts the base64 string into a byte array, creates a memory stream from the byte array, and creates a System.Drawing.Image object from the memory stream.

Finally, it saves the image to the specified path in JPEG format. If the process is successful, it returns a JSON response indicating success. If the base64 string is empty, it returns a JSON response indicating that content was not found. If an exception occurs during the process, it returns a JSON response with an error message.

Above code allows how to handle image uploads in a Web API controller by converting base64 encoded images into actual image files and saving them to the server.