springmvc中级-文件上传与下载

Spring MVC 为文件上传提供了直接的支持,这种支持是通 过即插即用的 MultipartResolver 实现的。Spring 用 Jakarta Commons FileUpload 技术实现了一个MultipartResolver 实现类:CommonsMultipartResovler

Spring MVC 上下文中默认没有装配 MultipartResovler,因 此默认情况下不能处理文件的上传工作,如果想使用 Spring 的文件上传功能,需现在上下文中配置 MultipartResolver

defaultEncoding: 必须和用户 JSP 的 pageEncoding 属性 一致,以便正确解析表单的内容。

为了让 CommonsMultipartResovler 正确工作,必须先 将 Jakarta Commons FileUpload 及 Jakarta Commons io 的类包添加到类路径下。

文件上传大白话:

1、添加文件上传的jar包

commons-fileupload-1.2.1.jar
commons-io-2.0.jar

2、编辑转发配置文件

<!-- 文件上传 配置  multipartresolver -->
<bean id="multipartResolver" 
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="102400"></property>
</bean>

3、网页测试页:

<form action="testFileUpload" method="post" enctype="multipart/form-data">
File:<input type="file" name="name-file"/>
Desc:<input type="text" name="name-desc"/>
<input type="submit" name="name-submit" value="submit" />
</form>

4、编辑控制器controler

@RequestMapping("/testFileUpload")
public String testFileUpload(@RequestParam("name-desc") String desc, 
		@RequestParam("name-file") MultipartFile file) throws IOException{
	System.out.println("name-desc: " + desc);
	System.out.println("OriginalFilename: " + file.getOriginalFilename());
	System.out.println("InputStream: " + file.getInputStream());
	return "success";
}

 

文件下载:

已经在HttpMessageConverter详解中的,ResponseEntity<byte[]>已经提到过了。

@RequestMapping("/testResponseEntity")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
	byte [] body = null;
	ServletContext servletContext = session.getServletContext();
	InputStream in = servletContext.getResourceAsStream("/files/abc.txt");
	body = new byte[in.available()];
	in.read(body);
		
	HttpHeaders headers = new HttpHeaders();
	headers.add("Content-Disposition", "attachment;filename=abc.txt");
		
	HttpStatus statusCode = HttpStatus.OK;
		
	ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
	return response;
}

 

 

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments