Connect with us

Springboot

How to upload Multipart File using Spring Boot REST API

springboot_file_upload

Handling image uploads is a common need for web applications. Whether you’re building a social media platform, an online store, or a content management system, knowing how to handle image uploads safely and efficiently is crucial. In this guide, we’ll look at how to do this using Spring Boot. We’ll also use the Postman tool to send the upload request and test it

This projewct is created on STS(spring tool suite ) IDE. You can choose any IDE to run this program.  Here is the Folder Structure.

 

 

   Create image folder like shown in the below image:

 

Controller.java

				
					package com.restupload.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.restupload.helper.Helper;

@RestController
public class Controller {

	@Autowired
	Helper fileUploadHelper;

	@PostMapping("/upload-file")
	public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {

		try {
			// Validation
			if (file.isEmpty()) {

				return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Request Must Contain File");
			}

			if (!file.getContentType().equals("image/png")) {

				return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Only Jpeg File type is allowed");
			}

			// File Upload

			boolean uploadFile = fileUploadHelper.uploadFile(file);
			if (!uploadFile) {
				System.out.println("null value");
			}
			if (uploadFile) {
				
				System.out.println(uploadFile);
				// ResponseEntity.ok("File Uploaded Successfully");
				return ResponseEntity.ok(ServletUriComponentsBuilder.fromCurrentContextPath().path("/image/")
						.path(file.getOriginalFilename()).toUriString());
			} else {
				return ResponseEntity.ok("Error Occured in File Uploaded");
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return ResponseEntity.ok("Working");
	}
}

				
			

Helper.java

				
					package com.restupload.helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Component
public class Helper {

	public static final String UPLOAD_DIR;

	static {
		String uploadDir;
		try {
			
			uploadDir = new ClassPathResource("static/image/").getFile().getAbsolutePath();
		} catch (IOException e) {
			
			uploadDir = "";
		}
		UPLOAD_DIR = uploadDir;
	}

	public boolean uploadFile(MultipartFile multipartFile) {

		boolean f = false;

		try {

			long copy = Files.copy(multipartFile.getInputStream(),
					Paths.get(UPLOAD_DIR + File.separator + multipartFile.getOriginalFilename()),
					StandardCopyOption.REPLACE_EXISTING);
			System.out.println(copy);
			f = true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return f;

	}
}

				
			

How to hit the end poin to upload the file

Upload Images will be saved in the  targate -> image folder

More in Springboot