一、上传
1、导包
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
2、在IOC容器中配置CommonsMultipartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="1048576"/>
</bean>
3、前台表单:别忘了设置enctype的值为multipart/form-data
<form action="${pageContext.request.contextPath }/upload" enctype="multipart/form-data" method="post">
文件一:<input type="file" name="file"/><br/>
文件二:<input type="file" name="file"/><br/>
文件三:<input type="file" name="file"/><br/>
<input type="submit" value="上传"/>
</form>
4、后台处理方法:前台传递来的File对象是个MultipartFile[]数组
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile[] files) throws IllegalStateException, IOException{
for (MultipartFile multipartFile : files) {
if(!multipartFile.isEmpty()){
multipartFile.transferTo(new File("D:\\" + multipartFile.getOriginalFilename()));
}
}
return "ok";
}
二、下载(无需导包)
1、前台超链接
<a href="${pageContext.request.contextPath }/download">下载</a>
2、后台处理方法:返回值采用ResponseEntity<T>
@Controller
public class DownloadHandler {
@RequestMapping(value="/download")
public ResponseEntity<byte[]> download() throws IOException{
//要下载的服务器端的文件
FileInputStream fis = new FileInputStream(new File("D://a.txt"));
byte[] content = new byte[fis.available()];
fis.read(content);
fis.close();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=a.txt");
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(content,headers,status);
return entity;
}
}