HomeFeaturedAboutContact
.NET
DotNet Web Api multipart/form-data – Upload using Bytes Array
Shehryar Khan
Shehryar Khan
March 11, 2022
1 min

Table Of Contents

01
Introduction
02
Uploading Image using Bytes Array
03
Testing Image Upload using Postman

Introduction

.Net Web API makes coding easier. They’re 2 most common ways of uploading image using .Net Web API.

  1. Uploading image using FormData (FromForm)
  2. Uploading Image using Bytes Array (FromBody)

In this article we’ll try uploading image using Bytes Array.

It actually depends on your requirements. If you want to send your Data in JSON From Body parameter, you cannot upload your image directly. In this case you need to convert image into a Bytes Array & send that to Server.

Most of the Developers face issue uploading images using Bytes Array. But it’s simple converting a byte stream into an image & save on the server using .Net Web API.

Uploading Image using Bytes Array

Let’s create a new Web API project.

We have created a new folder as images inside our wwwroot directory.

Here’s my code for converting Bytes Array to an Image & saving that image inside our images/wwwroot directory.

[HttpPost(nameof(UploadImageFromStream))]
public string UploadImageFromStream([FromBody]string strm)
{
    try
    {
        // getting images folder path
        string filepath = "wwwroot/images/MyImage.png";
        // converting base64 stream 
        var bytess = Convert.FromBase64String(strm);
        // converting to file
        using (var imageFile = new FileStream(filepath, FileMode.Create))
        {
            imageFile.Write(bytess, 0, bytess.Length);
            imageFile.Flush();
        }
        return "File Uploaded Successfully";
    }
    catch (Exception ex)
    {
        throw ex.InnerException;
    }
}

Testing Image Upload using Postman

First of all you need an Array of Image Bytes If you want to Test image uploading using Postman. There are many online websites that can convert your image into bytes array for testing. Here’s my Postman setting.

Screenshot 2022 06 30 at 11 53 40 AM 768x247

I’m able to upload & convert this to image successfully. If you are getting any issue, you can share in the comment section below.

Thank you for reading.


Tags

#webapi#multipart
Shehryar Khan

Shehryar Khan

Full-Stack .NET Developer

I'm passionate about learning new technologies as well as mentoring and helping others get started with their programming career. This blog is my way of giving back to the Community.

Expertise

.NET
ASP.NET
React

Social Media

instagramtwitterwebsite

Related Posts

Web API
Let’s Ready a .Net Core Web API Project
April 03, 2022
3 min
© 2023, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media