Skip to content

Commit 9de6fcc

Browse files
committed
Spring Boot 2.x基础教程:实现文件上传
1 parent bb70a13 commit 9de6fcc

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

2.x/chapter4-3/src/main/java/com/didispace/chapter43/UploadController.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
import java.io.File;
1313
import java.io.IOException;
14+
import java.nio.file.Files;
15+
import java.nio.file.Path;
1416

1517
@Controller
1618
@Slf4j
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,56 @@
1+
import com.didispace.chapter43.Chapter43Application;
2+
import org.junit.jupiter.api.BeforeEach;
13
import org.junit.jupiter.api.Test;
4+
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.boot.test.context.SpringBootTest;
6+
import org.springframework.http.MediaType;
7+
import org.springframework.mock.web.MockMultipartFile;
8+
import org.springframework.test.web.servlet.MockMvc;
9+
import org.springframework.test.web.servlet.MvcResult;
10+
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
11+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
12+
import org.springframework.web.context.WebApplicationContext;
213

14+
import java.io.IOException;
15+
16+
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
17+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
18+
19+
20+
@SpringBootTest(classes = Chapter43Application.class)
321
public class FileTest {
422

23+
@Autowired
24+
protected WebApplicationContext context;
25+
protected MockMvc mvc;
26+
27+
@BeforeEach
28+
public void setUp() {
29+
mvc = MockMvcBuilders.webAppContextSetup(context).build();
30+
}
31+
532
@Test
633
public void uploadFile() throws Exception {
34+
MockMultipartFile file = mockFile();
35+
36+
final MvcResult result = mvc.perform(
37+
MockMvcRequestBuilders
38+
.multipart("/upload")
39+
.file(file))
40+
.andDo(print())
41+
.andExpect(status().isCreated())
42+
.andReturn();
43+
}
744

45+
private MockMultipartFile mockFile() throws IOException {
46+
MockMultipartFile file = new MockMultipartFile(
47+
"file",
48+
"hello.txt",
49+
MediaType.TEXT_PLAIN_VALUE,
50+
"Hello, World!".getBytes()
51+
);
852

53+
return file;
954
}
1055

1156
}

0 commit comments

Comments
 (0)