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
The post C# -Saving a base64 string as an image into a folder on server in Web Api appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- C# - Download PDF from URL and convert it into base64 without saving it on a server
- Saving an image from the web to the Saved Pictures folder in Windows Phone 8.1 RT C#
- Sending an Image in Base64 Format over to an IIS server (hosting C#.net based Web Handler)
- Reading Image from Web Server in C# proxy
- web api action parameter convert empty string parameter to null
- Passing a time zone into a web api call from moment with nodatime
- How to save html2canvas image into System Folder in jquery
- Saving an Image to Photos Folder In hololens App
- Returning an image using Web API
- ASP.NET Core Web API 500 Internal Server Error
- Using Web API to deserialize into class with abstract property
- Image Uploading in Dot net core Web API
- Web Api 2 - Populating Default Values on Complex Query String Parameter
- How to Send Image as Base64String using Alamofire POST request and how to handle the request in Asp.net MVC4 web Api Controller?
- Adding Web API and folder references to empty ASP.NET project with Visual Studio 2012 Express for Web
- How to render a string containing HTML into an image in C#?
- Web API Controller - 'action' parameter in query string
- C# - Converting multi page tiff file to base64 string and converting back results with single image
- Convert HTML to Image using c#. Html has tags as well base64 string issue
- A generic error occurred in GDI+ while creating image from Base64 string
- Add OData to Web API 2 without coupling clients and server
- Pass SAML token into web api call
- pass value as empty string to WEb API from typescript
- Static variables in .net web api server
- How to handle optional query string parameters in Web API
- Error while converting string to DateTime after publishing to web server
- How to load an image from the server in a web application in C#
- Upload file into ASP.NET Core Web API
- Method to find Exchange Server version using Exchange Web Services (EWS) API
- Retrive image file from folder and display into Image Control
- Visual Studio 2010 project to Visual Studio 2012
- DataGridViewCheckBoxCell click handling issue
- The type arguments for methods cannot be inferred from the usage. Try specifying the type arguments explicitly
- I got stack overflow exception (infinite method call to ValidationResult ) in my wpf application
- How to export class libraries in Visual Studio 2012
- How to combine elements of a list
- The target "GetCopyToPublishDirectoryItems" does not exist in the project.
- automatic logging and statistics (C# application)
- Translation of yield into VB.NET
- Reading paged datagrids in Selenium Webdriver
- Using Fiddler as proxy for HttpWebRequest requires Fiddler to be running
- IIS 7.5 Application Pool Recycle not letting method finish
- Close a Window thats in the background
- AuthorizeAttribute with Roles not working when migrating from MVC to Endpoint Routing in ASP.NET Core 3.1
- common pattern, Here so I am trying to simplify it to reduce duplication
- Return By Reference in c#?
- Having VS 2012 installed but not .Net 4.5
- Unity Ads not working on android device, Advertisement.IsReady() comes back with false
- Excel automation: Any way of knowing how many pages a sheet will be printed out on?
- How to avoid of file name validation in SaveFileDialog C#