파일 업로드
pom.xml 추가
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
application.properties 설정
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB
file.upload.path=/Users/blake/
application.yml 설정
file:
upload:
path: /Users/blake/
spring:
servlet:
multipart:
max-file-size: 2MB
max-request-size: 2MB
resources 폴더에 templates 폴더를 만들고 안에 upload.html 파일을 만든다.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>upload webpage</title>
</head>
<body>
<h1>upload webpage</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
choose you upload file:<input type="file" name="file"><br>
<hr>
<input type="submit" value="submit">
</form>
</body>
</html>
Controller 를 작성한다.
@Controller
@Slf4j
public class UploadController {
@Value("${file.upload.path}")
private String path;
@GetMapping("/")
public String uploadPage() {
return "upload";
}
@PostMapping("/upload")
@ResponseBody
public String create(@RequestPart MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String filePath = path + fileName;
File dest = new File(filePath);
Files.copy(file.getInputStream(), dest.toPath());
return "Upload file success : " + dest.getAbsolutePath();
}
}
끝!
Last updated