文件上传:
Jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="img" />
<input type="submit" value="上传" />
</form>
<img src="${path}">
</body>
</html>
Handler:
@Controller
@RequestMapping("/file")
public class FileHandler {
@PostMapping("/upload")//单文件上传
public String upload(MultipartFile img, HttpServletRequest request){
System.out.println(img);
if(img.getSize()>0){
//获取保存上传到tomcat文件的路径
String path = request.getServletContext().getRealPath("");//
//获取上传的文件名
String name = img.getOriginalFilename();
/* //手动创建文件夹
String dirname = path+"/file";
File d = new File(dirname);
d.mkdir();*/
File file = new File(path,name);
try {
img.transferTo(file);//上传文件
request.setAttribute("path","/"+name);
} catch (IOException e) {
e.printStackTrace();
}
}
return "upload";
}
}
web.xml 记得添上配置
<servlet-mapping> <!-- 静态资源 .jpg -->
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping> <!-- 静态资源 .png -->
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
若不添加配置,客户端⽆法访问 jpg或png (图片文件上传能成功,但无法在视图预览):
正常上传情况:
文件下载:
Jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="/file/download/233">1.jpg</a> <%-- Rest风格url 不用.jpg (后缀会被截取) --%>
<a href="/file/download/234">2.jpg</a>
<a href="/file/download/235">3.jpg</a>
</body>
</html>
Handler
@GetMapping("/download/{name}") //下载文件 超链接是get请求
public void download(@PathVariable("name") String name,HttpServletRequest request , HttpServletResponse response){ //rest 记得@PathVariable 传统的话同名不用@RequestParam
if (name != null) {
name=name+".jpg";
String path = request.getServletContext().getRealPath("/");
File file = new File(path,name);
OutputStream outputStream =null;
if(file.exists()){
response.setContentType("application/forc-download");
response.setHeader("Content-Disposition","attachment;filename="+name);
try {
outputStream = response.getOutputStream();
outputStream.write(FileUtils.readFileToByteArray(file));
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(outputStream !=null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
下载结果: