SpringBoot快速整合Thymeleaf实现文件上传案例
文章目录
- SpringBoot快速整合Thymeleaf实现文件上传案例
- 1. 创建工程
- 2. pom.xml文件
- 2. application.yml 配置
- 3. 前端fileupload.html
- 4. 后端Controller
本案例环境:
- SpringBoot: 2.3.0.RELEASE
- JDK: 1.8
- 前端模板: thymeleaf
1. 创建工程
- 在IDEA中通过SpringBoot初始化向导创建一个工程,如取名为
yuan-fileupload
- 创建完工程后按下面的步骤进行配置即可完成文件上传功能。
2. pom.xml文件
pom.xml文件上引入相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.0.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>org.yuan</groupId><artifactId>yuan-fileupload</artifactId><version>0.0.1-SNAPSHOT</version><name>yuan-fileupload</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><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.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
2. application.yml 配置
server:port: 8085
spring:servlet:multipart:max-file-size: 1GB # 用于设置上传文件的最大大小,默认值为1MB。如果上传的文件大小超过这个限制,则会导致上传失败max-request-size: 2GB # 参数用于设置整个请求的最大大小,包括所有文件和表单数据,默认值为10MB。如果请求大小超过这个限制,Spring Boot 将拒绝接收请求,并返回一个异常
3. 前端fileupload.html
通过thymeleaf进行进行文件上传,前端
fileupload.html
页面内容如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>文件上传案例</title>
</head>
<body><form method="post" enctype="multipart/form-data" th:action="${#httpServletRequest.getContextPath()}+'/fileUpload'">文件1: <input type="file" name="files"><br>文件2: <input type="file" name="files"><br><input type="submit" value="上传">
</form>
</body>
</html>
4. 后端Controller
FileUploadController.Java如下,支持多文件上传
package org.yuan.yuanfileupload.fileupload;import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.yuan.yuanfileupload.utils.ResultMsg;import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;/*** <p>* Description: 文件上传简单案例 <br>* <p>* Author:jinshengyuan <br>* Datetime: 2020/5/24 14:55* </p>** @since 2020/5/24 14:55*/
@Controller
public class FileUploadController {/*** <p>* Description: 跳转至文件上传页面的handler <br>* <p>* Author:jinshengyuan <br>* Datetime: 2020/5/24 14:56* </p>** @return 跳转的模板名称* @since 2020/5/24 14:56*/@RequestMapping("/initUpload")public String initUpload() {return "fileUpload";}/*** <p>* Description: 文件上传方法<br>* <p>* Author:jinshengyuan <br>* Datetime: 2020/5/24 14:57* </p>** @return 返回上传后的处理结果* @since 2020/5/24 14:57*/@ResponseBody@RequestMapping("/fileUpload")public ResultMsg fileUpload(MultipartFile[] files, HttpServletRequest request) throws Exception {for (MultipartFile file : files) {String contentType = file.getContentType();String originalFilename = file.getOriginalFilename();String name = file.getName();System.out.println("contentType:" + contentType);System.out.println("originalFilename:" + originalFilename);System.out.println("name:" + name);//文件名不为空则上传if (!StringUtils.isEmpty(originalFilename)) {//文件存放位置//1.传统的方式获取服务器跟目录下的fileUpload路径//String realPath = request.getServletContext().getRealPath("/fileUpload");//2.Springboot项目中获取resource/static/fileupload路径String uploadPath = ResourceUtils.getURL("classpath:").getPath() + "static/fileUpload/";System.out.println("uploadPath:" + uploadPath);//文件输出目录是否存在,不存在则创建File dir = new File(uploadPath);if (!dir.exists()) {dir.mkdir();}//文件名前缀 日期+UUIDString fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + UUID.randomUUID().toString().replace("-", "");//文件后缀名String fileExtendName = FilenameUtils.getExtension(originalFilename);//输出到指定的位置String outFileName = fileNamePrefix.concat(".").concat(fileExtendName);//文件上传至指定目录file.transferTo(new File(dir, outFileName));} else {//文件名为空,跳出当前循环continue;}}return ResultMsg.success();}
}