MultipartFile
- 파일 업로드시 사용하는 메소드 아규먼트
- MultipartResolver 빈이 설정되어 있어야 사용 가능 (Sringboot 기본 제공)
- POST multipart/form-data 요청에 들어있는 파일을 참조할 수 있다.
- List<MultipartFile> 아규먼트로 여러 파일을 참조 가능
package com.example.demo;
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 org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class FileController {
@GetMapping("/file")
public String fileUploadForm(Model model) {
return "files/index";
}
@PostMapping("/file")
public String fileUpload(@RequestParam MultipartFile file , RedirectAttributes attributes) {
String message = file.getOriginalFilename() + " is uploaded";
attributes.addFlashAttribute("message",message);
return "redirect:/file";
}
}
<index.html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="EUC-KR">
<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>
<Test Code>
package com.example.demo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class FileControllerTest {
//@SpringBootTest
//전반적인 웹 어플리케이션의 테스트를 하려면 @SpringBootTest
//@SpringBootTest는 모든 빈들이 등록은 되지만 MockMvc를 만들어주지 않는다. 그래서 @AutoConfigureMockMvc 가 필요
@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());
}
}
'Spring > SpringMVC' 카테고리의 다른 글
[Spring MVC] @ModelAttribute 와 Model (0) | 2019.08.23 |
---|---|
[Spring MVC] 응답 타입 @ResponseBody & ResponseEntity (0) | 2019.08.22 |
[Spring MVC] Flash Attributes (0) | 2019.08.20 |
[Spring MVC] RedirectAttributes (0) | 2019.08.19 |
[Spring MVC] @SessionAttribute (0) | 2019.08.19 |