springboot 项目实现文件上传
application.yaml 配置文件内容
spring:
servlet:
multipart:
max-request-size: 5GB # 上传文件总的最大值 默认10MB
max-file-size: 1GB #单个文件最大值 默认10MB
# 文件保存的目录
upload: D:\Users\zdz\IdeaProjects\fileupload\upload\
controller代码:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
public class UpLoadController {
@Value("${upload}")
String filePath;
@PostMapping("/upload")
public Object upload(@RequestParam("file") MultipartFile file){
return saveFile(file);
}
@PostMapping("/multiUpload")
public Object multiUpload(@RequestParam("file")MultipartFile[] files){
System.out.println("文件的个数:"+files.length);
for (MultipartFile f : files){
saveFile(f);
}
return "ok";
}
private Object saveFile(MultipartFile file){
if (file.isEmpty()){
return "未选择文件";
}
String filename = file.getOriginalFilename();
File temp = new File(filePath);
if (!temp.exists()){
temp.mkdirs();
}
File localFile = new File(filePath+filename);
try {
file.transferTo(localFile);
System.out.println(file.getOriginalFilename()+" 上传成功");
}catch ( IOException e){
e.printStackTrace();
return "上传失败";
}
return "ok";
}
}
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body>
<center>
<h3>上传文件</h3>
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file" required><br>
<input type="submit" value="上传单个文件">
</form>
</center>
</body>
</html>