upload multipart file spring boot

Multipart File Upload Spring Boot

In this post, we will learn to upload a Multipart File using Spring Boot. If you want to learn how to implement it in angular then you can visit upload multipart file in angular.

Let’s see an example code that accepts the MultipartFile and saves it into the project’s default directory.

1. Create Spring Boot Project

If you don’t know how to create a Spring Boot project then you can refer to our previous post Create Spring Boot project using Spring Initialzer where I have written about it in detail.

2. FileUploadController class

package com.codersathi;

import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/uploads")
public class FileUploadController {

	@PostMapping
	public String uploadFile(@RequestPart("file")  MultipartFile multipartFile) {
		try {
			FileOutputStream fout = new FileOutputStream(multipartFile.getOriginalFilename());
			fout.write(multipartFile.getBytes());
			return "Success!";
		} catch (IOException e) {
			e.printStackTrace();
			return "Failed!";
		}
	}
}

The above code is a Spring Boot controller class that accepts the MultipartFile from the client and saves it into the default directory of the project.

3. Test by uploading multipart file using Postman REST client

To test MultipartFile upload, we can use Postman a REST client. You can download Postman from the link download postman.

After the download is complete you can install and open it.

  1. Got to Body tab and
  2. Select form-data
  3. In the key give value file
  4. Select File and
  5. Upload file by clicking Choose Files button.
  6. Click Send button.
Multipart File Upload Spring Boot upload multipart file spring boot 1
Multipart File Upload Spring Boot 3

After clicking Send button the file should be uploaded successfully.

4. Conclusion

In this post, we learned to upload a Multipart File in Spring Boot Project.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments