Implement as the title of the article. The following functions will be implemented this time. -Upload by specifying the image path from the input screen composed of HTML form and input tag -Output the file to the specified directory via Java
Modify the following 3 files
Controller
java:com.example.SampleController.java
@RequestMapping(path = "/sample/upload", method = RequestMethod.GET)
String uploadview(Model model) {
return "sample/upload";
}
@RequestMapping(path = "/sample/upload", method = RequestMethod.POST)
String upload(Model model, UploadForm uploadForm) {
if (uploadForm.getFile().isEmpty()) {
return "sample/upload";
}
// check upload distination directory.If there was no directory, make
// func.
Path path = Paths.get("/Users/demo-kusa/image");
if (!Files.exists(path)) {
try {
Files.createDirectory(path);
} catch (NoSuchFileException ex) {
System.err.println(ex);
} catch (IOException ex) {
System.err.println(ex);
}
}
int dot = uploadForm.getFile().getOriginalFilename().lastIndexOf(".");
String extention = "";
if (dot > 0) {
extention = uploadForm.getFile().getOriginalFilename().substring(dot).toLowerCase();
}
String filename = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(LocalDateTime.now());
Path uploadfile = Paths
.get("/Users/demo-kusa/image/" + filename + extention);
try (OutputStream os = Files.newOutputStream(uploadfile, StandardOpenOption.CREATE)) {
byte[] bytes = uploadForm.getFile().getBytes();
os.write(bytes);
} catch (IOException ex) {
System.err.println(ex);
}
return "redirect:/sample";
}
ActionForm
java:com.example.UploadForm.java
package com.example;
import org.springframework.web.multipart.MultipartFile;
public class UploadForm {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
template
src/main/resources/templates/sample/upload.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>top page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h2>Image upload</h2>
<form method="post" enctype="multipart/form-data" action="/sample/upload" >
<input name="file" type="file" />
<input type="submit" value="Send"/>
</form>
</body>
</html>
This article has partially replaced the environment-dependent part, but the source is below, so if you need it, please. github kaikusakari/spring_crud
Recommended Posts