在Spring Boot中实现单文件,多文件上传

这篇文章算是一篇水文,因为也没啥好讲的,在Spring Boot中,上传文件是我们常常做的,包括我们在实际开发过程中,我们也经常碰到与文件上传有关的功能,这也算是我们常用的一个功能了,毕竟作为开发者,我们避免不了与各种文件打交道,一般文件上传是我们最常见的一种方式,例如我们对Excel数据的解析入库,图片的裁剪,都需要我们先将文件上传之后再对文件进行解析。

注意本篇博客,主要适合初学者,如果不感兴趣,可以移步了。

单文件上传

本篇,我将采用Thymeleaf模版引擎进行,故而第一步,我们还是引入相关依赖。

xml 复制代码
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

在application.properties文件中配置存放地址,以及允许上传的文件的大小

properties 复制代码
server.port=1243
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB

file.upload.path=D:/test/
java 复制代码
@Controller
@Slf4j
public class UploadController {

    @Value("${file.upload.path}")
    private String path;

    @GetMapping("/")
    public String uploadPage() {
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String create(@RequestPart MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String filePath = path + fileName;
        File dest = new File(filePath);

        Files.copy(file.getInputStream(), dest.toPath());
        return "上传本地文件路径: " + dest.getAbsolutePath();
    }

}
html 复制代码
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>文件上传页面</title>
</head>
<body>
<h1>文件上传页面</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
    选择要上传的文件:<input type="file" name="file"><br>
    <hr>
    <input type="submit" value="提交">
</form>
</body>
</html>

通过浏览器,localhost:1243

这里仅仅是一个案例,在实际开发过程中,我们需要考虑更多,比如文件上传后的文件我们需要进行相关处理,一般可以添加时间日期等预防同名,在分布式服务下,我们需要考虑文件如何共享访问等等。

多文件上传

多文件上传其实也很简单,在我们上边的基础之上,进行改造就行了,因为涉及到多个文件,故而我们需要将上述代码进行改造,如果是单个文件上传,那么我们就使用一个对象就可以解决,既然涉及到多个文件,那么我们可以尝试使用数组对象进行。

还是之前的那样,第一步先引入依赖:
注意:这里的依赖和上述依赖一模一样,毫无变化,配置文件也是。

xml 复制代码
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
properties 复制代码
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB

server.port=1243

file.upload.path=D:/test/

在前端页面上,我多加了一个文件提交按钮。

html 复制代码
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>文件上传页面</title>
</head>
<body>
<h1>文件上传页面</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
    文件1:<input type="file" name="files"><br>
    文件2:<input type="file" name="files"><br>
    <hr>
    <input type="submit" value="提交">
</form>
</body>
</html>

文件上传控制类:

java 复制代码
@Controller
@Slf4j
public class UploadController {

    @Value("${file.upload.path}")
    private String path;

    @GetMapping("/")
    public String uploadPage() {
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    //主要这里,我们改造的地方,由单个对象变成了数组对象
    public String create(@RequestPart MultipartFile[] files) throws IOException {
        StringBuffer message = new StringBuffer();
		//循环遍历出数组对象
        for (MultipartFile file : files) {
        	//为了避免文件名同名,我加了日期前置,你也选择精确的具体时间
            String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String fileName = date + file.getOriginalFilename();
            String filePath = path + fileName;

            File dest = new File(filePath);
            Files.copy(file.getInputStream(), dest.toPath());
            message.append("文件上传成功 : " + dest.getAbsolutePath()).append("<br>");
        }
        return message.toString();
    }

}

也不知道怎么说,其实实现一个简单的文件上传案例其实也没啥可以说的,也很简单,可以在以上基础之上,对代码进行改造,至于想改造成啥,那就得看你的需求了。

相关推荐
2601_962056236 小时前
Spring Boot 入门 与 无法解析符号 springframework 的解决
java·spring boot·后端
学长毕业设计7 小时前
基于SpringBoot的瑜伽馆网站的设计与实现(源码+文档+讲解视频)
java·spring boot·后端
学长毕业设计10 小时前
基于springboot的云南中草药知识普及管理网站的设计与开发(源码+文档+讲解视频)
java·spring boot·后端
小江的记录本11 小时前
【AI Agent】《2026年9月 AI Agent全栈开发技术选型专项面试宝典》
java·spring boot·python·spring·ai·面试·ai编程
摇滚侠12 小时前
《SpringBoot 3:入门与应用实战》第 9 章 使用 WebMvc 开发应用 阅读笔记 2
java·spring boot·笔记
步行cgn12 小时前
@RestController 详解:从源码到实践
spring boot
边境悍匪13 小时前
springboot常用注解
java·spring boot·学习
李昊哲小课14 小时前
Spring Boot 4 旅游主题实战教程 阶段四:缓存与底层进阶
spring boot·redis·缓存·性能优化·log4j·旅游·性能
QQ_216962909615 小时前
【源码编号:project93375】SpringBoot汽车维修管理信息系统:客户车辆、维修预约、工单派发、配件结算全流程实战
java·spring boot·后端·汽车·springboot·需求分析
xcl092515 小时前
流浪宠物领养管理系统开发实战:从需求分析到落地的完整指南
java·spring boot·需求分析·宠物