Dot Tutorials
.Net Core

.Net Core Web Api multipart/form-data – upload File with Form Data

.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.

This article will also be helpful for you:

Upload Image/Video/File using Form Data .Net 6 | .Net 5

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

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.

Here’re some more related articles you must read:

– A COMPLETE GUIDE TO SECURE YOUR ASP.NET CORE WEB API

– TOP OPEN SOURCE ASP.NET CORE CONTENT MANAGEMENT SYSTEM (CMS)

– HOW TO CREATE SOAP WEB SERVICES IN DOTNET CORE

Author

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.

3 Comments

  1. Andrei Arekhva Reply

    Perfect article, that’s what I need! Thank you very much

  2. sandeep kumar chintalapally Reply

    Thanks , its perfect article for my need.

Write A Comment