Spring Boot中进行 文件上传和 文件下载功能实现
作者:一只大皮卡丘
一、SpringBoot中进行 " 文件上传" :
开发Wb应用时,文件上传是很常见的一个需求,浏览器 通过 表单形式 将 文件 以 流的形式传递 给 服务器,服务器再对上传的数据解析处理。下面将通过一个案例讲解使用 SpringBoot 实现 文件上传,具体步骤 如下 :
1.编写 “文件上传” 的 “表单页面”
在项目的 templates模板引擎文件夹下创建一个用来上传文件的upload.html模板页面 :
upload.html :
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>动态添加文件上传列表</title>
<link th:href="@{/login/css/bootstrap.min.css}" rel="external nofollow" rel="stylesheet">
<script th:src="@{/login/js/jquery-3.7.1.min.js}"></script>
</head>
<body>
<div th:if="${uploadStatus}" style="color: red" th:text="${uploadStatus}">
上传成功</div>
<form th:action="@{/uploadFile}" method="post" enctype="multipart/form-data">
上传文件:
<input type="button" value="添加文件" onclick="add()"/>
<div id="file" style="margin-top: 10px;" th:value="文件上传区域"> </div>
<input id="submit" type="submit" value="上传"
style="display: none;margin-top: 10px;"/>
</form>
<script type="text/javascript">
function add(){
var innerdiv = "<div>";
innerdiv += "<input type='file' name='fileUpload' required='required'>" +
"<input type='button' value='删除' οnclick='remove(this)'>";
innerdiv +="</div>";
$("#file").append(innerdiv);
$("#submit").css("display","block");
}
function remove(obj) {
$(obj).parent().remove();
if($("#file div").length ==0){
$("#submit").css("display","none");
}
}
</script>
</body>
</html>2.在全局配置文件中添加文件上传的相关配置
在 全局配置文件 : application.properties中添加文件上传的相关设置,配置如下 :
application.properties :
spring.application.name=chapter_12 #thymeleaf的页面缓存设置(默认为true),开发中为方便调试应设置为false,上线稳定后应保持默认true spring.thymeleaf.cache=false ##配置国际化文件基础名 #spring.messages.basename=i18n.login #单个文件上传大小限制(默认为1MB) spring.servlet.multipart.max-file-size=10MB #总文件上传大小限制 spring.servlet.multipart.max-request-size=50MB
在 application.properties 全局配置文件中,对文件 上传过程中的上传大小进行了设置。
3.进行文件上传处理,实现 “文件上传” 功能
FileController.java :
package com.myh.chapter_12.controller;
import org.springframework.boot.Banner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* 文件管理控制类
*/
@Controller //加入到IOC容器中
public class FileController { //关于File的controller类
@GetMapping("/toUpload")
public String toUpload(){
return "upload";
}
@PostMapping("/uploadFile")
public String uploadFile(MultipartFile[] fileUpload, Model model) {
//默认文件上传成功,并返回状态信息
model.addAttribute("uploadStatus", "上传成功!");
for (MultipartFile file : fileUpload) {
//获取文件名以及后缀名 (获取原始文件名)
String fileName = file.getOriginalFilename();
//使用UUID + 原始文件名 来生成一个新的文件名
fileName = UUID.randomUUID()+"_"+fileName;
//指定文件上传的本地存储目录,不存在则提前创建
String dirPath = "S:\\File\\";
File filePath = new File(dirPath);
if(!filePath.exists()){filePath.mkdirs();}//创建该目录
try {
//执行“文件上传”的方法
file.transferTo(new File(dirPath+fileName));
}
catch (Exception e) {e.printStackTrace();
//上传失败,返回失败信息
model.addAttribute("uploadStatus","上传失败: "+e.getMessage());}
}
//携带状态信息回调到文件上传页面
return "upload";
}
}4.效果测试
启动项目,在浏览器访问 http://localhost:8080/toUpload ,效果如下图所示 :



通过以上图片可以看出,SpringBoot 中进行 “文件上传”成功 。
二、SpringBoot中进行 “文件下载” :
下载文件能够通过IO流实现,所以 多数框架并没有对文件下载进行封装处理。文件下载时涉及不同浏览器的解析处理,可能会出现 中文乱码 的情况。
接下来将针对 下载英文名文件 和 中文名文件 进行讲解。
“英文名称” 文件下载 : 1.添加文件下载工具依赖
在 pom.xml文件中引入文件下载的一个工具依赖 :
<!-- 文件下载的工具依赖 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>2.定制文件下载页面
download.html :
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>"英文名称"文件下载</title></head><body>
<div style="margin-bottom: 10px">文件下载列表:</div>
<table>
<tr>
<td>嘻嘻哈哈123.txt</td>
<td><a th:href="@{/download(filename='5afa8ee7-6cbf-4632-9965-4df31aad4558_嘻嘻哈哈123456.txt')}" rel="external nofollow" >下载该文件</a></td>
</tr>
<tr>
<td>嘻嘻哈哈123456.txt</td>
<td><a th:href="@{/download(filename='c53a27b1-b42e-41a4-b283-86ac43034203_嘻嘻哈哈123.txt')}" rel="external nofollow" >下载该文件</a></td>
</tr>
</table>
</body>
</html>上面代码中通过列表展示了要下载的两个 文件名及其下载链接。需要注意的是,在文件下载之前,需要保证在文件下载目录(本示例中的“S:\File”目录)中存在对应的文件,可以自行存放,只要 保持文件名统一 即可。
3.编写文件下载处理方法
FileController.java :
package com.myh.chapter_12.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.Banner;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;
/**
* 文件管理控制类
*/
@Controller //加入到IOC容器中
public class FileController { //关于File的controller类
@GetMapping("/toDownload")
public String toDownload(){
return "download";
}
/**
* 英文名称文件下载
*/
@GetMapping("/download")
public ResponseEntity<byte[]> fileDownload(String filename){
//指定要下载的文件根路径
String dirPath = "S:\\File\\";
//创建该文件对象
File file = new File(dirPath + File.separator + filename);
//设置响应头
HttpHeaders headers = new HttpHeaders();
//通知浏览器以下载方式打开
headers.setContentDispositionFormData("attachment",filename);
//定义以流的形式下载返回文件数据
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try {return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.OK);}
catch (Exception e) {e.printStackTrace();
return new ResponseEntity<byte[]>(e.getMessage().getBytes(),
HttpStatus.EXPECTATION_FAILED);
}
}
}4.效果测试
启动项目,在浏览器访问 http://localhost:8080/toDownload ,效果如下图所示 :


“中文名称” 文件下载 : 1.添加文件下载工具依赖
在 pom.xml文件中引入文件下载的一个工具依赖 :
<!-- 文件下载的工具依赖 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>2.定制文件下载页面
download.html :
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>中文名称文件下载</title></head><body>
<div style="margin-bottom: 10px">文件下载列表:</div>
<table>
<tr>
<td>嘻嘻哈哈123456.txt</td>
<td><a th:href="@{/download(filename='708ebc14-2ca7-4b66-b0bf-3b9c65df6ec1_嘻嘻哈哈123456.txt')}" rel="external nofollow" >下载该文件</a></td>
</tr>
<tr>
<td>嘻嘻哈哈123.txt</td>
<td><a th:href="@{/download(filename='418b0e77-59dc-4697-8a62-6a450d466567_嘻嘻哈哈123.txt')}" rel="external nofollow" >下载该文件</a></td>
</tr>
</table>
</body>
</html>上面代码中通过列表展示了要下载的两个 文件名及其下载链接。需要注意的是,在文件下载之前,需要保证在文件下载目录(本示例中的“S:\File”目录)中存在对应的文件,可以自行存放,只要 保持文件名统一 即可。
3.编写文件下载处理方法
FileController.java :
package com.myh.chapter_12.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.Banner;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;
/**
* 文件管理控制类
*/
@Controller //加入到IOC容器中
public class FileController { //关于File的controller类
@GetMapping("/toDownload")
public String toDownload(){
return "download";
}
/**
* "中文名称"文件下载
*/
@GetMapping("/download")
public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename) throws Exception{
//指定下载的文件根路径
String dirPath = "S:\\File\\";
//创建该文件对象
File file = new File(dirPath + File.separator + filename);
//设置响应头
HttpHeaders headers = new HttpHeaders();
//通知浏览器以下载方式打开(下载前对文件名进行转码)
filename=getFilename(request,filename);
headers.setContentDispositionFormData("attachment",filename);
//定义以流的形式下载返回文件数据
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try {return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.OK);} catch (Exception e) {e.printStackTrace();
return new ResponseEntity<byte[]>(e.getMessage().getBytes(),
HttpStatus.EXPECTATION_FAILED);
}
}
//根据浏览器的不同进行编码设置,返回编码后的文件名
private String getFilename(HttpServletRequest request,String filename)
throws Exception {
//IE不同版本User-Agent中出现的关键词
String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
//获取请求头代理信息
String userAgent = request.getHeader("User-Agent");
for (String keyWord : IEBrowserKeyWords) {
if (userAgent.contains(keyWord)) {
//IE内核浏览器,统一为UTF-8编码显示,并对转换的+进行更正
return URLEncoder.encode(filename, "UTF-8").replace("+"," ");
}}
//火狐等其他浏览器统一为ISO-8859-1编码显示
return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
}4.效果测试
启动项目,在浏览器访问 http://localhost:8080/toDownload ,效果如下图所示 :


到此这篇关于Spring Boot中进行 “文件上传” 和 “文件下载”的文章就介绍到这了,更多相关Spring Boot文件上传和 文件下载内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
