一,文件上传
(1)导入包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
(2)设置xml文件
<!--配置上传组件-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
(3)handler
首先需要在 target/工程/下新建file文件夹
@Controller
@RequestMapping("/file")
public class FileHandler {
@PostMapping("/upload")
public String upload(MultipartFile picture, HttpServletRequest request) {
if (picture.getSize() > 0) {
// 获取保存的路径(绝对路径)
String path = request.getSession().getServletContext().getRealPath("file");
// 获取文件名
String filename = picture.getOriginalFilename();
File file = new File(path, filename);
try {
picture.transferTo(file);
// 上传后的图片地址
request.setAttribute("img", "/file/" + filename);
} catch (IOException e) {
e.printStackTrace();
}
}
return "upload";
}
(4)jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/file/upload" enctype="multipart/form-data" method="post">
<input type="file" name="picture">
<input type="submit" value="上传">
</form>
<img src="${img}">
</body>
</html>
二,文件下载
(1)handler
@GetMapping("/download/{name:.+}")
public void download(@PathVariable("name") String name, HttpServletRequest request, HttpServletResponse response) {
if (name != null) {
// name = name + ".jpg";
File file = new File(request.getSession().getServletContext().getRealPath("file"), name);
if (file.exists()) {
response.setContentType("application/forc-download");
response.setHeader("Content-Disposition", "attachment;filename=" + name);
try {
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(FileUtils.readFileToByteArray(file));
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
(2)jsp
<body>
<!--不加最后的/会报404-->
<a href="/file/download/1.jpg/">1.jpg</a>
</body>
(3)解决rest无法识别.
spring会将rest中的点,识别为/分隔符,所以 .jpg等会出现识别错误的情况。可以这样写:{name:.+}
解决