欢迎访问个人原创博客:德鲁大叔撸代码
几乎在所有的软件中都会有上传文件的需求,自己动手写一个在springboot项目中的文件上传功能
具体步骤如下:
一、引入依赖(基础依赖在父工程的pom文件中)
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.27</version>
</dependency>
<!-- thymeleaf模板插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
二、编写配置文件
server:
port: 9999
servlet:
context-path: /
spring:
thymeleaf:
cache: false
http:
multipart:
//单个文件的最大值
maxFileSize: 1Mb
//多个文件的最大值
maxRequsetSize: 5Mb
三、文件上传的核心逻辑
@Controller
public class FileController {
@RequestMapping("file")
public String file(){
return "file";
}
/**
* 单文件上传
* @param file
* @return
*/
@PostMapping("/upload")
@ResponseBody
public String fileUpload(@RequestParam("filename")MultipartFile file){
if(file.isEmpty()){
return "上传文件为空";
}
//上传文件的全路径
String fileName = file.getOriginalFilename();
int size = (int)file.getSize();
System.err.println("文件大小为:"+size);
//文件的上传路径
String path = "D:/test";
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdir();
}try {
file.transferTo(dest);
return "上传成功";
}catch (IllegalStateException e){
return "上传失败";
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
/**
* 多文件上传
* @param request
* @return
*/
@RequestMapping(value="multifileUpload",method=RequestMethod.POST)
public @ResponseBody String multifileUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");
if (files.isEmpty()) {
return "上传文件为空";
}
String path = "D:/test";
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
if (file.isEmpty()) {
return "上传文件为空";
} else {
File dest = new File(path + "/" + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "上传失败";
}
}
}
return "上传成功";
}
}