Load Image With Spring Boot and Thymeleaf (#12486)

* Load Image With Spring Boot and Thymeleaf

* Load Image With Spring Boot and Thymeleaf
This commit is contained in:
ACHRAF TAITAI
2022-08-04 10:49:11 +02:00
committed by GitHub
parent 81b05fb3ac
commit d24f73002a
3 changed files with 59 additions and 1 deletions
@@ -0,0 +1,31 @@
package com.baeldung.thymeleaf.imageupload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller public class UploadController {
public static String UPLOAD_DIRECTORY = System.getProperty("user.dir") + "/uploads";
@GetMapping("/uploadimage") public String displayUploadForm() {
return "imageupload/index";
}
@PostMapping("/upload") public String uploadImage(Model model, @RequestParam("image") MultipartFile file) throws IOException {
StringBuilder fileNames = new StringBuilder();
Path fileNameAndPath = Paths.get(UPLOAD_DIRECTORY, file.getOriginalFilename());
fileNames.append(file.getOriginalFilename());
Files.write(fileNameAndPath, file.getBytes());
model.addAttribute("msg", "Uploaded images: " + fileNames.toString());
return "imageupload/index";
}
}