Spring Boot实现文件上传下载
作者:云淡风轻58 时间:2021-11-22 21:19:36
本文实例为大家分享了Spring Boot实现文件上传下载的具体代码,供大家参考,具体内容如下
示例【Spring Boot 文件上传下载】
程序清单:/springboot2/src/main/resources/templates/register.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>注册</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" >
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" />
<script type="text/javascript" th:src="@{js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Spring Boot文件上传</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-8">
<form action="upload" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="input-group col-md-4">
<span class="input-group-addon">
<i class="glyphicon glyphicon-user"></i>
</span>
<input class="form-control" type="text" name="userName">
</div>
</div>
<div class="form-group">
<div class="input-group col-md-4">
<span class="input-group-addon">
<i class="glyphicon glyphicon-search"></i>
</span>
<input class="form-control" type="file" name="head">
</div>
</div>
<div class="form-group">
<div class="col-md-4">
<button type="submit" class="btn btn-success">注册</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
程序清单:/springboot2/src/main/resources/templates/userInfo.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" >
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" />
<script type="text/javascript" th:src="@{js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Spring Boot文件下载</h3>
</div>
</div>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">用户信息列表</h3>
</div>
</div>
<div class="panel-body">
<div class="table table-responsive">
<table class="table table-bordered" id="userTable">
<tbody class="text-center">
<tr>
<td><img th:src="@{'upload/'+${user.head.originalFilename}}" height="30"></td>
<td th:text="${user.userName}">用户名</td>
<td><a th:href="@{download(filename=${user.head.originalFilename })}" >下载</a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
程序清单:/springboot2/src/main/java/com/dwx/hello/User.java
package com.dwx.hello;
import org.springframework.web.multipart.MultipartFile;
public class User {
private String userName;
private MultipartFile head;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public MultipartFile getHead() {
return head;
}
public void setHead(MultipartFile head) {
this.head = head;
}
}
程序清单:/springboot2/src/main/java/com/dwx/hello/UserController.java
package com.dwx.hello;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
@RequestMapping("/registerForm")
public String registerForm() {
return "register";
}
@RequestMapping("/upload")
public String upload(HttpServletRequest request,
@ModelAttribute User user,Model model) throws IllegalStateException, IOException {
if(!user.getHead().isEmpty()) {
String path=request.getServletContext().getRealPath("/upload");
String fileName=user.getHead().getOriginalFilename();
File filePath=new File(path,fileName);
if(!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
user.getHead().transferTo(new File(path+File.separator+fileName));
model.addAttribute("user", user);
return "userInfo";
}else {
return "error";
}
}
@RequestMapping(value="/download")
public ResponseEntity<byte[]> download(HttpServletRequest request,
@RequestParam("filename") String filename,
@RequestHeader("User-Agent") String userAgent,
Model model)throws Exception{
// 下载文件路径
String path = request.getServletContext().getRealPath(
"/upload/");
// 构建File
File file = new File(path+File.separator+ filename);
// ok表示Http协议中的状态 200
BodyBuilder builder = ResponseEntity.ok();
// 内容长度
builder.contentLength(file.length());
// application/octet-stream : 二进制流数据(最常见的文件下载)。
builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
// 使用URLDecoder.decode对文件名进行解码
filename = URLEncoder.encode(filename, "UTF-8");
// 设置实际的响应文件名,告诉浏览器文件要用于【下载】、【保存】attachment 以附件形式
// 不同的浏览器,处理方式不同,要根据浏览器版本进行区别判断
if (userAgent.indexOf("MSIE") > 0) {
// 如果是IE,只需要用UTF-8字符集进行URL编码即可
builder.header("Content-Disposition", "attachment; filename=" + filename);
} else {
// 而FireFox、Chrome等浏览器,则需要说明编码的字符集
// 注意filename后面有个*号,在UTF-8后面有两个单引号!
builder.header("Content-Disposition", "attachment; filename*=UTF-8''" + filename);
}
return builder.body(FileUtils.readFileToByteArray(file));
}
}
运行Spring Boot项目,访问以下地址:http://localhost:8080/registerForm
来源:https://blog.csdn.net/dwenxue/article/details/82841707
标签:Spring,Boot,上传,下载
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SpringBoot Java后端实现okhttp3超时设置的方法实例
2022-11-06 04:56:03
浅析Java线程的中断机制
2023-11-19 20:11:50
详解SpringBoot注册Windows服务和启动报错的原因
2022-12-28 17:10:09
![](https://img.aspxhome.com/file/2023/1/63431_0s.jpg)
详解Java的引用类型及使用场景
2021-06-27 11:34:18
什么是递归?用Java写一个简单的递归程序
2022-02-11 19:39:45
![](https://img.aspxhome.com/file/2023/2/60772_0s.jpg)
JAVA JVM面试题总结
2021-07-12 04:55:13
![](https://img.aspxhome.com/file/2023/0/62390_0s.png)
Gradle的安装和环境变量的配置详解
2023-07-11 04:56:37
![](https://img.aspxhome.com/file/2023/2/83552_0s.png)
微信小程序微信登录的实现方法详解(JAVA后台)
2023-08-29 12:37:25
![](https://img.aspxhome.com/file/2023/0/58370_0s.jpg)
JVM(Java虚拟机)简介(动力节点Java学院整理)
2023-11-25 06:12:12
![](https://img.aspxhome.com/file/2023/7/58867_0s.png)
Java文件操作之按行读取文件和遍历目录的方法
2023-11-24 16:58:21
Java使用通配符实现增强泛型详解
2021-07-06 17:28:01
![](https://img.aspxhome.com/file/2023/2/60282_0s.png)
JAVA 格式化日期、时间的方法
2023-10-17 07:53:22
java中如何截取字符串最后一位
2023-11-27 00:51:16
![](https://img.aspxhome.com/file/2023/6/60376_0s.png)
解决Mybatis的@Param()注解导致分页失效的问题
2022-05-01 13:24:53
![](https://img.aspxhome.com/file/2023/0/63400_0s.jpg)
Java中的static关键字你了解多少
2022-05-21 11:25:51
![](https://img.aspxhome.com/file/2023/9/65609_0s.jpg)
springboot使用之多个filter的执行顺序以及配置方式
2023-11-09 09:30:59
![](https://img.aspxhome.com/file/2023/5/59045_0s.jpg)
C# WinForm制作登录界面的实现步骤
2022-09-06 18:32:54
![](https://img.aspxhome.com/file/2023/7/68607_0s.png)
Spring Bean生命周期之BeanDefinition的合并过程详解
2023-11-29 02:50:35
JavaFX实现UI美观效果代码实例
2021-08-27 21:02:15
![](https://img.aspxhome.com/file/2023/6/62206_0s.jpg)
Mybatis无法获取带有下划线前缀的字段的值问题
2023-07-20 10:06:33
![](https://img.aspxhome.com/file/2023/3/62173_0s.png)