How to Upload Multiple Images in Spring boot
They are so many developers who asked how to upload multiple images through the spring boot framework. Today I will share some code examples with you guys on how to do it more straightforwardly.
Lets Start!
my project structure;
File Upload Util Class
import java.io.IOException
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class FileUploadUtil {
? ? public? static? void saveFile(String uploadDir, String fileName, MultipartFile multipartFile) throws IOException {
? ? ? ? Path uploadPath= Paths.get("C:\\Users\\User\\Downloads\\img\\img\\src\\main\\resources\\static\\"+uploadDir);
? ? ? ? if (!Files.exists(uploadPath)){
? ? ? ? ? ? Files.createDirectories(uploadPath);
? ? ? ? }
? ? ? ? try(InputStream inputStream= multipartFile.getInputStream()) {
? ? ? ? ? ? Path filePath=uploadPath.resolve(fileName);
? ? ? ? ? ? Files.copy(inputStream,filePath, StandardCopyOption.REPLACE_EXISTING);
? ? ? ? }catch (IOException ioException){
? ? ? ? }
? ? }
};
Image Upload Controller Class
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
@RequestMapping("api/v1/img")
@RestController
public class ImageUploadController {
@PostMapping("/upload")
public void saveImage(@RequestParam("files")MultipartFile[] files){
String uploadDir="profileImagesFolder";
Arrays.asList(files).stream().forEach(file->{
String fileName= StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
System.out.println(fileName);
try {
FileUploadUtil.saveFile(uploadDir,fileName,file);
}catch (IOException ioException){
}
});
}
}
;
Postman TESTING!
@udarasan
Thanks, Me Later... Happy Coding!