Spring MVC文件上传下载
单文件上传
介绍:底层是使用 Apache fileupload 组件完成上传,Spring MVC 对这种方式进行了封装。
步骤如下:
1、先在pom.xml中导入相关依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
2、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>
几点说明:
- 文件上传,input的type属性需要设置成"file"
- form标签中的method需设置成"post",因为get请求只能将文件名上传给服务器
- form标签中的enctype设置为 multipart-form-data,否则只能将文件名上传给服务器
3、Handler
package com.zyc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@Controller
@RequestMapping("/file")
public class FileHandler {
@PostMapping("/upload")
public String upload(MultipartFile img, HttpServletRequest request){
if(img.getSize()>0){
//获取保存上传文件的file路径
String path = request.getServletContext().getRealPath("file");
//获取上传的文件名
String name = img.getOriginalFilename();
File file = new File(path,name);
try {
img.transferTo(file);
//保存上传之后的文件路径
request.setAttribute("path","/file/"+name);
} catch (IOException e) {
e.printStackTrace();
}
}
return "upload";
}
}
4、在spring-mvc.xml中配置上传组件
<!-- 配置上传组件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
5、web.xml 添加如下配置,否则客户端无法访问 png
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
多文件上传
JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/file/uploads" method="post" enctype="multipart/form-data">
file1:<input type="file" name="imgs"/><br/>
file2:<input type="file" name="imgs"/><br/>
file3:<input type="file" name="imgs"><br/>
<input type="submit" value="上传"/>
</form>
<c:forEach items="${files}" var="file" >
<img src="${file}" width="300px">
</c:forEach>
</body>
</html>
Handler
扫描二维码关注公众号,回复:
12435634 查看本文章

@PostMapping("/uploads")
public String uploads(MultipartFile[] imgs,HttpServletRequest request){
List<String> files = new ArrayList<>();
for (MultipartFile img:imgs){
if(img.getSize()>0){
//获取保存上传文件的file路径
String path = request.getServletContext().getRealPath("file");
//获取上传的文件名
String name = img.getOriginalFilename();
File file = new File(path,name);
try {
img.transferTo(file);
//保存上传之后的文件路径
files.add("/file/"+name);
} catch (IOException e) {
e.printStackTrace();
}
}
}
request.setAttribute("files",files);
return "uploads";
}
@PostMapping:映射了一个POST请求
为Spring MVC的新特性,提供了对Restful风格的支持
文件下载
JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="/file/download/1">1.png</a>
<a href="/file/download/2">2.png</a>
<a href="/file/download/3">3.png</a>
</body>
</html>
Handler
@GetMapping("/download/{name}")
public void download(@PathVariable("name") String name, HttpServletRequest request, HttpServletResponse response){
if(name != null){
name += ".png";
String path = request.getServletContext().getRealPath("file");
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 {
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
@GetMapping,处理get请求