HomeFeaturedAboutContact
.NET
DotNet Web Api multipart/form-data – upload File with FormData
Shehryar Khan
Shehryar Khan
July 28, 2021
2 min

Table Of Contents

01
Introduction
02
Sending Files & JSON using multipart/form-data
03
Testing with Postman

Introduction

.Net Core Web API provides a Scalable, Maintainable, Secure & Simple way for writing powerful APIs. Choosing the right tool for writing API for your Client App is a crucial thing & no doubt that Dotnet Core considered as one of the great choices to do the job.

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)

Writing Restful Services using .Net Core is really simple when we send data from Client to Server in the form of JSON but sometimes developers find it difficult to upload files on the Server along with JSON Data.

There’re several ways to Upload an Image as well as submit Form Data in a single request.

  1. Send Image bytes as Base64 using JSON Data.
  2. Send Image & Form-based data in separates requests.
  3. Use Multipart request type to achieve this target of sending text & image together.

All the above methods will work fine but sending the Large Image as Base64 using JSON is not a good idea. It will take a lot of memory & time for converting back to the actual image for copying on the Server. If we use two separate API for sending Files & JSON data, it’s also not a good practice & can be problematic if the image does problem while uploading but JSON data submitted successfully & we need both on the server at the same time.

Sending Files & JSON using multipart/form-data

So In this article, we’re going to use Multipart approach for uploading files along with JSON Data. Files can be of any format like an image, pdf, Xls, doc, ppt, mp4 or any other format.

For achieving this .Net Core Web API provides IFormFile type. Unfortunately, there is no build-in support available for receiving JSON Data with files but fortunately, it’s really simple to create a custom Model according to our requirement of receiving data on the server-side.

Let’s start by creating a Model for your Multipart Data.

Assume that you want to receive Name & Image of a Student.

Your StudentModel will look something like this.

using Microsoft.AspNetCore.Http;

public class StudentModel {

    public string Name { get; set; }
    public IFormFile Image { get; set; }
}

You can see that we are using IFormFile for receiving Photo.

Let’s see how we can use this Model in our Web Service.

[HttpPost("api/student")]
public ActionResult Student([FromForm]StudentModel std)
{
    // Getting Name
    string name = std.Name;

    // Getting Image
    var image = std.Image;

    // Saving Image on Server
    if (image.Length > 0) {
        using (var fileStream = new FileStream(image.FileName, FileMode.Create)) {
            image.CopyTo(fileStream);
        }
    }

    return Ok(new { status = true, message = "Student Posted Successfully"});
}

[FromForm] is compulsory to use with StudentBody parameter for getting Files with JSON Data.

image.CopyTo(fileStream); is saving our Image on Server.

You can also save your Files on a specific location by combining the Path. For example,

var filePath = Path.Combine("wwwroot/images", image.FileName);

Now, you’ll replace image.FileName in FileStream object with filePath variable.

Testing with Postman

Run your project & call your service using Postman by selecting form-data in Body

upload file

I hope everything will work perfectly at your end as well. Still, If you find any problem, please let me know in the comment section below or you can email me for any related query.


Tags

#webapi#formdata
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