SpringBoot
实现文件上传到指定项目路径
- 导入依赖:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.6.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.1</version>
</dependency>
- 新增控制器文件
TestController.java
:
package com.study.controller;
import com.study.utils.UploadUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class TestController {
// 跳转上传页面
@RequestMapping("/")
public String test() {
return "index";
}
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile imgFile, Model model){
// 拿到文件名
String filename = imgFile.getOriginalFilename();
// 存放上传图片的文件夹
File fileDir = UploadUtils.getImgDirFile();
// 输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
System.out.println(fileDir.getAbsolutePath());
try {
// 构建真实的文件路径
File newFile = new File(fileDir.getAbsolutePath() + File.separator + filename);
System.out.println(newFile.getAbsolutePath());
// 上传图片到 -》 “绝对路径”
imgFile.transferTo(newFile);
} catch (IOException e) {
e.printStackTrace();
}
// 将src路径发送至html页面
model.addAttribute("filename", UploadUtils.IMG_PATH_PREFIX + filename);
return "index";
}
}
- 新增目录工具类
UploadUtils.java
:
package com.study.utils;
import java.io.File;
public class UploadUtils {
// 项目根路径下的目录 -- SpringBoot static 目录相当于是根路径下(SpringBoot 默认)
public final static String IMG_PATH_PREFIX = "static/upload/images";
public static File getImgDirFile(){
// 构建上传文件的存放 "文件夹" 路径
String fileDirPath = new String("src/main/resources/" + IMG_PATH_PREFIX);
File fileDir = new File(fileDirPath);
if(!fileDir.exists()){
// 递归生成文件夹
fileDir.mkdirs();
}
return fileDir;
}
}
Resources
目录下新增templates/index.html
前端页面文件:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="../upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*">
<br>
<input type="text" value="">
<input type="submit" value="上传" class="btn btn-success">
</form>
[[${filename}]]
<br>
<img th:src="@{${filename}}" alt="图片">
</body>
</html>
- 测试访问:
http://localhost:8080
上传成功后,将会在 resources/static/upload/images
目录下新增加一个上传后的文件,表示文件上传成功了。
温馨提示:这是粗略版实现,可以根据需求进行进一步精简优化。