springboot 文件上传

2024-10-15 19:36:02

1、新建springboot项目,如下图

springboot 文件上传

2、编辑pom.xml文件,引入依赖内容如下:<dependency> <groupId>org.springframework.boot&造婷用痃lt;/groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version></dependency<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId></dependency><!-- 添加HikariCP依赖 --<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId></dependency<!-- thymeleaf依赖 --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>

springboot 文件上传

3、编辑application.yml文件文件内容如下:server: port: 8080spring: datasource: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/aadb?useSSL=false&useUnicode=true&characterEncoding=utf8 username: root password: 123456 servlet: multipart: max-file-size: 10MB max-request-size: 10MB thymeleaf: mode: HTML5 encoding: UTF-8 servlet: content-type: text/html

springboot 文件上传

4、在resources\templates目录下新建upload.html文件内容如下:<html><h髫潋啜缅ead> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <title>单文件上传</title></head><body><form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="file"><br> <input type="submit" value="提交"></form></body></html>

springboot 文件上传

5、新建UploadController内容如下:@Controllerpublic class UploadController { 刺胳挤萧@GetMapping("/upload") public String upload() { return "upload"; } @PostMapping("/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "上传失败,请选择文件"; } String fileName = file.getOriginalFilename(); String filePath = "D://"; File dest = new File(filePath + fileName); try { file.transferTo(dest); return "上传成功"; } catch (IOException e) { //log e.printStackTrace(); } return "上传失败!"; }}

springboot 文件上传

6、启动springboot项目

springboot 文件上传

7、打开浏览器,输入地址http://localhost:8080/upload

springboot 文件上传

8、点击“选择文件”>"打开"

springboot 文件上传

9、点击“提交”

springboot 文件上传

10、提示上传成功,到相应目录查看,我嚓还真多了一个文件😮

springboot 文件上传springboot 文件上传
猜你喜欢