新搭建了一个springboot 框架项目,调试完使用的过程,写文件上传接口,发现一直报错:
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("files") List<MultipartFile> files) {
// Process the uploaded files
for (MultipartFile file : files) {
// You can access each file's content using file.getInputStream(), file.getBytes(), etc.
// Process the files as needed.
}
return "Upload successful";
}
}
采坑1:
Required request part 'fileList' is not present RequestPartMethodArgumentResolver.resolveArgument
网上各种原因,最终发现是springboot 2.7版本针对
spring.mvc.hiddenmethod.filter.enabled=true配置,默认为false, 在springboot的旧版本中,默认是true.
解决:
在application.properties文件中,增加该配置即可
采坑2:
springboot 多文件上传异常:MultipartFile resource [fileList] cannot be resolved to URL
分析:
由于是采用form-data 格式:multipart/form-data,初步分析是 springboot 在接收到fileList时,form表单的格式无法解析为json序列化,具体还待后面细分析
初步解决思路:
本意是多文件批量上传,如此不行,则继续单文件上传,转换思路是把多文件压缩为zip文件,然后服务端接收到后,再行解压,即可
先附上chatgpt 生成的解压文件代码,后面验证:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@RestController
public class ZipController {
@PostMapping("/unzip")
public String unzip(@RequestParam("zipFile") MultipartFile zipFile) {
try {
File destDir = new File("unzipped");
if (!destDir.exists()) {
destDir.mkdirs();
}
try (ZipInputStream zipInputStream = new ZipInputStream(zipFile.getInputStream())) {
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String entryName = zipEntry.getName();
File entryFile = new File(destDir, entryName);
if (entryFile.getParentFile() != null) {
entryFile.getParentFile().mkdirs();
}
if (!zipEntry.isDirectory()) {
try (FileOutputStream fos = new FileOutputStream(entryFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = zipInputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
}
}
}
// 遍历解压后的文件
for (File file : destDir.listFiles()) {
if (file.isFile()) {
System.out.println("File: " + file.getName());
} else if (file.isDirectory()) {
System.out.println("Directory: " + file.getName());
}
}
return "ZIP文件解压缩成功并遍历完成";
} catch (IOException e) {
e.printStackTrace();
return "ZIP文件解压缩失败";
}
}
}