Spring Test之文件上传篇

Spring Test之文件上传篇

1、上传需要的简单配置

1.1 导入依赖包,包含文件上传、springtest4+和Junit4+包

<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.3.8.RELEASE</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.3</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

1.2  在springMVC的配置文件上传bean,如下:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8"/>
		<property name="maxUploadSize" value="1024000000"/>
	</bean>
上述代码中,defaultEncoding表示文件上传编码格式,maxUploadSize表示允许上传的文件大小。

2、创建controller

@RequestMapping("/file")
@Controller
public class fileUpController {
	
	@ResponseBody
	@PostMapping("/up")
	public String upFile(@RequestParam("file") MultipartFile multipartFile,Model model){
		
		String isSuccesString = "success";
		File file = new File("D:\\files\\");
		//创建文件夹
		file.mkdirs();
		try {
			//写入新创建的文件夹
			multipartFile.transferTo(new File(file, "fileName"));
		} catch (Exception e) {
			isSuccesString = "fail";
		}
		return isSuccesString;
	}
}

3、创建测试类

3.1 简单文件上传(不通过io流)

@WebAppConfiguration
@ContextConfiguration({"classpath:spring-context.xml","classpath:spring-mvc.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class MockTest {
	
	private static final Logger LOGGER = Logger.getLogger(MockTest.class);
	@Autowired
	private WebApplicationContext wbc;
	
	MockMvc mockMvc;
	
	@Before
	public void init(){
		//创建MockMvc对象
		this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wbc).build();
	}
	
	@Test
	public void test1() {
		
		try {
			ResultActions contentAsString = this.mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file/up")
									.file("file", "文件内容".getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
		}
步骤:
(1)首先创建MockMvc对象
(2)调用MockMvc中的方法perform(RequestBuilder requestBuilder),该方法接收一个RequestBuilder对象。通过查看源码,spring推荐我们使用MockMvcRequestBuilders:



该类有着丰富的http请求方法,比如get、post等,其中有fileUpload()方法用于文件上传。


fileUpload()参数表示文件上传的url地址,再调用file(String name,byte[] content)方法选择上传的文件,第一个参数表示请求的key,第二个参数表示文件的内容。这里接收的是一个byte类型的数组,但是并没有设置文件名的地方,查看源码可知,file()方法内部调用了MockMultipartFile类的构造函数,默认的文件名是 “ ”:



但是文件名在哪写呢?第一个方法就是在Controller中的multipartFile.transferTo(new File(file, "fileName"));写上文件名,例如fileName.很明显这样做是不合适的,毕竟上传的文件名不可能写死。第二种方法就是使用file()方法的另外一个重载方法

该方法接收一个MockMultipartFile的对象,该类有很多重载的构造函数:

3.2 通过io流上传

更换file()方法,测试方法修改为:
 @Test
    public void test() {
		
		try {
		InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("spring-mvc.xml");
		ResultActions contentAsString = this.mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file/up")
					.file(new MockMultipartFile("file","spring-mvc.xml","text/html",resourceAsStream)));
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

通过使用file()的重载方法,我们可以指定方法名,以及通过io流上传文件。构造方法如下:

从源码注释可以很清楚看到:name表示参数接收的key,originalFilename代表文件名,contentType表示文件类型,contentStream表示文件输入流。
这样,在Controller方法中,我们可以修改为
multipartFile.transferTo(new File(file, multipartFile.getOriginalFilename()));
通过上面两种方法运行之后,就会在D:\files文件夹下知道上传的文件。

 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
   

猜你喜欢

转载自blog.csdn.net/sinat_30160727/article/details/77865992