Working with static files

Upload files with base64 to an ASP.NET Core API

I this tutorial, I'll show you how to upload a file to a .net core API using base64

When you need to upload a file to an API in ASP.NET Core, the easiest way is to use the IFormFile. In Microsoft documentation, IFormFile represents a file sent with the HttpRequest.

With IFormFile, the request is made with form-data. Although send a class with a complex structure it will be hard to request with form-data because we can't use JSON on the body.

A cool way to continue use JSON is converting the file to base64, and send the content on body raw too.

For purpose tests, you can convert your file to base64 here. On output format, choose JSON. Save the content, you'll need later.

First, we need to create a class to receive our base64 content like the following.

Create an action on a controller to accept the class Base64File.

In this action, we need to do the following steps:

1) Get the file extension

2) Generate a unique name base on the date

3) Create the full path of the file

4) Convert file to array of bytes

5) Save the file

Before testing, we need to create a folder named wwwroot on the solution root folder.

Run the application, and open the swagger on the browser. Copy the base64 content created before and try.

A new file should be on the folder wwwroot!!

Now we need to create a way to access the files.

On the startup.cs file add the following instructions. This will allow accessing the files on wwwroot by URL.

Copy the name of the uploaded file, run the API, and put it on the browser URL like: https://localhost:5001/xxx.png.

If everything is fine, you should see your file!!

You can find the repo on my GitHub

Hope you enjoyed it and learned something new!

Header image from unsplash

Do you have any doubt, or did you detect an error? Contact me!