0:00 / 7:24
Spring Boot Tutorial: Upload Files via REST API

In this is video I want to talk about how you can upload a file using Spring Boot controller and REST API.

I will show this example from an actual project and you can find all the links in description.

So let's start I have a Spring Boot project

. If you've watched my previous videos, I also updated project structure a little. So now I have all the relevant parts under one package.

But for this file upload part, I have a file package. And the idea with this package is to provide features for uploading files even like managing files.

That's why I have a file controller. Like this is a generic part of the generic name for this. Because I plan to introduce more operations for file editing. And it is exposed on this endpoi nt. So v1 (version 1) / file one file. And for now I have a one method, which is post mapping Method is called upload. Everthing that user will send to this endpoint will be processed by this. Later, we can also set up a separate URL for this, but for now I will keep it s imple.

This method accepts two parameters. One is a file itself. And another one is a name. And internally this will d o first thing, which is like, get file and name into this FileUploadRequest. Which again, this a file and it contains file and name. So for this model, interesting part is type of the file is MultipartFile. From org.springframework.web.multipart. And name is just a string.

But the interesting part which makes all this work is how we set up this post mapping. First thing we say we consume a multi-part form data value. You can also put string here, but this is what we need to mention explicitly. I also additional inputproduces which is I say that returns a JSON value and this value is actually is another type a record in my case, And it is, it has like ID because I saved information metadata about the file into the database. Name user-defined name. URL and size.

So let's also take a look to the service part. After basically parsing file input. I sent it to the service layer. Which also has an operation named upload.

What we have is I return a response entity and then say, this is okay. Maybe we can also change it to created or something like similar. And then say it's uploaded a and an upload.