想要实现文件的上传,必须将表单设置为method=”post”,enctype="multipart/form-data",这样才能将所选文件的二进制数据发送到服务器,springboot引入的“spring-boot-starter-web”,已经集成了springMVC,所以springboot实现文件上传,只需要引入commons-fileupload的依赖即可
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
</dependencies>
在全局配置文件中设置上传文件的大小限制
spring.thymeleaf.cache=false
spring.web.resources.static-locations= classpath:/static/
spring.mvc.static-path-pattern= /static/**
#设置单个文件上传大小限制
spring.servlet.multipart.max-file-size= 50MB
#设置总文件大小限制
spring.servlet.multipart.max-request-size=500MB
新建一个文件上传页面upload.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" th:href="@{/static/easyui/themes/default/easyui.css}">
<link rel="stylesheet" type="text/css" th:href="@{/static/easyui/themes/icon.css}">
<link rel="stylesheet" type="text/css" th:href="@{/static/easyui/themes/color.css}">
<link rel="stylesheet" type="text/css" th:href="@{/static/easyui/themes/xyy.css}">
<script type="text/javascript" th:src="@{/static/easyui/jquery.min.js}"></script>
<script type="text/javascript" th:src="@{/static/easyui/easyloader.js}"></script>
</head>
<body>
<form id="ff" method="post" action="upload" enctype="multipart/form-data">
<div>
<label>选择文件</label>
<input name="myfile" class="easyui-filebox" style="width:300px">
<input type="submit" value="提交">
</div>
</form>
</body>
</html>
新建一个文件下载页面download.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" th:href="@{/static/easyui/themes/default/easyui.css}">
<link rel="stylesheet" type="text/css" th:href="@{/static/easyui/themes/icon.css}">
<link rel="stylesheet" type="text/css" th:href="@{/static/easyui/themes/color.css}">
<link rel="stylesheet" type="text/css" th:href="@{/static/easyui/themes/xyy.css}">
<script type="text/javascript" th:src="@{/static/easyui/jquery.min.js}"></script>
<script type="text/javascript" th:src="@{/static/easyui/easyloader.js}"></script>
<script>
function formatterFileName(value,row,index) {
return '<a href="javascript:void(0)" onclick="downloadFile(\''+row.filename+'\')">'+value+'</a>'
}
function downloadFile(filename) {
window.location.href="download?filename="+filename;
}
</script>
</head>
<body>
<table class="easyui-datagrid" style="width:900px;height:500px"
data-options="url:'showDownload',fitColumns:true,singleSelect:true">
<thead>
<tr>
<th data-options="field:'filename',width:100,formatter:formatterFileName">文件名称</th>
</tr>
</thead>
</table>
</body>
</html>
后端方法
@Controller
@RequestMapping("thymeleaf")
public class ThymeLefaController {
/**
*@Description TODO
*@Author Administrator
*@Date 2022/4/6 10:14
*@Version 1.0
*/
@RequestMapping("test")
public String test(){
//thymeleaf模板 默认将返回到src/main/resources/templates/index.html
return "index";
}
@RequestMapping("touploadFile")
public String touploadFile(){
//thymeleaf模板 默认将返回到src/main/resources/templates/index.html
return "upload";
}
/**
* 上传文件自动绑定到MultipartFile对象中
* */
@RequestMapping("upload")
public String upload(HttpServletRequest request, @RequestParam("myfile") MultipartFile myfile) throws IOException {
//如果附件不为空 将附件上传到目录uploadFiles目录下
if(!myfile.isEmpty()){
//文件上传路径
String path = request.getServletContext().getRealPath("/uploadFiles/");
//获取上传文件的原名
String filename = myfile.getOriginalFilename();
File filePath = new File(path + File.separator + filename);
if(!filePath.getParentFile().exists()){
filePath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件中
myfile.transferTo(filePath);
}
return "download";
}
/**
* 获取要下载的文件
* **/
@RequestMapping("showDownload")
@ResponseBody
public List<Map<String,Object>> showDownload(HttpServletRequest request, Model model){
List<Map<String, Object>> list = new ArrayList<>();
String path = request.getServletContext().getRealPath("/uploadFiles/");
File fileDir = new File(path);
//指定目录获取文件列表
File[] files = fileDir.listFiles();
for (int i = 0; i < files.length; i++) {
Map<String, Object> map = new HashMap<>();
map.put("filename",files[i].getName());
list.add(map);
}
return list;
}
/**
* 下载文件
* **/
@RequestMapping("download")
public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename, @RequestHeader("User-Agent") String userAgent) throws IOException {
//下载文件路径
String path = request.getServletContext().getRealPath("/uploadFiles/");
//构建将要下载的文件对象
File downFile = new File(path + File.separator + filename);
//设置http状态码为200
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
//内容长度
builder.contentLength(downFile.length());
//设置二进制流数据
builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
//对文件名进行编码
filename = URLEncoder.encode(filename,"UTF-8");
//设置响应文件,不同的浏览器 处理方式不同
if(userAgent.indexOf("MSIE") > 0){
//如果是ie浏览器,只需要用UTF-8 进行url编码
builder.header("Content-Disposition","attachment;filename=" + filename);
}else{
//非IE浏览器,需要说明编码字符集
builder.header("Content-Disposition","attachment;filename * =UTF-8''" + filename);
}
return builder.body(FileUtils.readFileToByteArray(downFile));
}
}