1.上传
jsp form表单file提交
<form action="${pageContext.request.contextPath}/UpDown/UpLoad.do" method="post" enctype="multipart/form-data">
<input type="file" name="files"/>
<input type="file" name="files"/>
<input type="submit"/>
</form>
controller
@RequestMapping("/UpLoad")
public String upLoad(MultipartFile[] files,String userName) throws IOException {
for (MultipartFile file : files) {
String fileName = UUID.randomUUID().toString();
int dex = file.getOriginalFilename().lastIndexOf(".");
fileName += file.getOriginalFilename().substring(dex);
File toFile = new File("E:\\uploadFiles",fileName);
toFile.createNewFile();
file.transferTo(toFile);
}
return "OK";
}
导包
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>```
spring-mvc.xml中配置
```
下载
@RequestMapping("/downLoad/{fileName:.+}.do")//".+"为了处理http URL中不能出现“.”
@ResponseBody
public String downLoad(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
File file = new File("E:\\uploadFiles");
File outFile = new File(file,fileName);
if(!outFile.exists()){
return "the file is not exist!";
}
byte[] bytes = new byte[1024*1024];
response.setHeader("content-disposition","attchment;filename=" + URLEncoder.encode(fileName,"utf-8"));
//告诉浏览器,现在响应一个二进制流
response.setContentType("application/octet-stream");
InputStream is = new FileInputStream(outFile);
ServletOutputStream sos = response.getOutputStream();
int len = 0;
while((len = is.read(bytes))!= -1){
sos.write(bytes,0,len);
}
sos.flush();
is.close();
sos.close();
return "OK";
}