使用postman測試多文件上傳接口
1、創建測試類(FileController.java)
package com.jeff.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
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;
@RestController
public class FileController {
@PostMapping("/upload")
public String upload(@RequestParam("files") List<MultipartFile> files) {
if (files.isEmpty()) {
return "上傳失敗,未選擇文件";
}
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
// 獲取文件后綴名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 重新生成文件名
String fName = System.currentTimeMillis() + suffixName;
System.out.println("文件名:" + fName);
String filePath = "F:\\Jeff\\project\\workspace\\mavenDemo\\src\\main\\resources\\static\\";
File dest = new File(filePath + fName);
try {
file.transferTo(dest);
System.out.println(fName + "上傳成功!");
} catch (IOException e) {
System.out.println(fName + "上傳異常!" + e);
return "error";
}
}
return "success";
}
}
2、使用postman測試多文件上傳接口(選擇多個文件)
3、查看項目路徑
4、如果報下圖錯誤,請查看 解決方法
解決方法:The field files exceeds its maximum permitted size of 1048576 bytes
錯誤原因:
SpringBoot的默認上傳文件的大小是1M,如果上傳的文件超過了1M就會出現這樣的錯誤
解決方法:
在application.properties配置文件中設置上傳的文件大小限制,即可解決
# 上傳文件總的最大值
spring.servlet.multipart.max-request-size=10MB
# 單個文件的最大值
spring.servlet.multipart.max-file-size=10MB
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_45739720/article/details/103724064