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 Mobile App and I got a requirement to upload images by Andriod App So that I decided to take the image as Base64 from the API and Save it to the server folder. After completing it my task, I decided to share 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
Add comment