1.基本配置
(1) 导包
(2) 配置springmvc.xml
<!-- 在 SpringMvc 配置文件中配置文件上传组件工具类 -->
<!--id值不可更改-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 通过属性来规范上传文件的信息 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 上传文件的最大的字节数 -->
<property name="maxUploadSize" value="5000000"></property>
</bean>
2.上传
<form method="post" enctype="multipart/form-data" action="doUpload">
//上传文件必须为"post"
<input type="text" name="name"><br>
<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
@RequestMapping("/doUpload")
public String doUpload(@RequestParam(value = "file") MultipartFile[] multipartFiles) {
//设置上传路径
String path = "D://doUpload//";
//没有文件夹,创建文件夹
File file = new File(path);
if (!file.exists()){
file.mkdirs();
}
if (multipartFiles != null&&multipartFiles.length>0) {
for (MultipartFile multipartFile : multipartFiles) {
// 获取文件名称
String filename = multipartFile.getOriginalFilename();
//构建文件对象
File file1 = new File(path + filename);
try {
multipartFile.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "success";
}
3.下载
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>filter.jsp</title>
</head>
<body>
<a href="download?filename=xiazai.txt">下载</a> //拼接url
</body>
</html>
@RequestMapping(value = "/download")
public ResponseEntity<byte[]> download(String filename) {
String filePath = "E://Download//";
File file = new File(filePath + filename);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attchment", filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ResponseEntity<byte[]> entity = null;
try {
// 利用 springMVC 的工具将指定的 File 对象中文件编译成字节数组
entity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
}
return entity;
}