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:
parent
81b05fb3ac
commit
d24f73002a
|
@ -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";
|
||||
}
|
||||
}
|
|
@ -1 +1,3 @@
|
|||
#spring.thymeleaf.prefix=classpath:/templates-2/
|
||||
spring.servlet.multipart.max-file-size = 5MB
|
||||
spring.servlet.multipart.max-request-size = 5MB
|
|
@ -0,0 +1,25 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
|
||||
</head>
|
||||
<body>
|
||||
<section class="my-5">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-8 mx-auto">
|
||||
<h2>Upload Image Example</h2>
|
||||
<p th:text="${message}" th:if="${message ne null}" class="alert alert-primary"></p>
|
||||
<form method="post" th:action="@{/upload}" enctype="multipart/form-data">
|
||||
<div class="form-group">
|
||||
<input type="file" name="image" accept="image/*" class="form-control-file">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Upload image</button>
|
||||
</form>
|
||||
<span th:if="${msg != null}" th:text="${msg}"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</body>
|
||||
</html>
|
Loading…
Reference in New Issue