MultipartFile
파일 업로드 관련 스프링 부트 설정
파일 업로드 폼
<form method="POST" enctype="multipart/form-data" action="#" th:action="@{/file}"> File: <input type="file" name="file"/>
<input type="submit" value="Upload"/>
</form>
파일 업로드 처리 핸들러
@PostMapping("/file")
public String uploadFile(@RequestParam MultipartFile file,
RedirectAttributes attributes) {
String message = file.getOriginalFilename() + " is uploaded.";
System.out.println(message);
attributes.addFlashAttribute("message", message);
return "redirect:/events/list";
}
메시지 출력
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
<form method="POST" enctype="multipart/form-data" action="#" th:action="@{/file}"> File: <input type="file" name="file"/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
@Controller
public class FileController {
@GetMapping("/file")
public String fileUploadForm(Model model){
return "files/index";
}
@PostMapping("/file")
public String fileUpload(@RequestParam MultipartFile file,
RedirectAttributes attributes){
// save
System.out.println("file name : " + file.getName());
System.out.println("file original name : " + file.getOriginalFilename());
String message = file.getOriginalFilename() + " is uploaded";
attributes.addFlashAttribute("message", message);
return "redirect:/file";
}
}
테스트 코드
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class FileControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void fileUploadTest() throws Exception{
MockMultipartFile file = new MockMultipartFile("file", "test.txt", "text/plain", "hello file".getBytes());
this.mockMvc.perform(multipart("/file").file(file))
.andDo(print())
.andExpect(status().is3xxRedirection());
}
}
참고