springBoot 同时上传多张图片且携带请求参数
一、背景
需要同时上传多张图片,同时需要携带请求参数
二、实现
点击查看代码
@AnonymousPostMapping("/insertWeighbridgeRecord")
@Log("第三方新增地磅称重记录")
@ApiOperation("第三方新增地磅称重记录")
@PreAuthorize("@el.check('weighbridgeRecord:add')")
public ResponseEntity<Object> createWeighbridgeRecord(@Validated @RequestPart WeighbridgeRecord resources,@RequestPart("file") List<MultipartFile> file) throws IOException {
List<Map<String, Object>> mapList = new ArrayList<>();
if(ObjectUtil.isEmpty(resources)){
throw new IllegalArgumentException("新增参数实体不能为空!!!");
}
// 校验图片
validPic(resources, file, mapList);
return new ResponseEntity<>(weighbridgeRecordService.create(resources),HttpStatus.CREATED);
}
private void validPic(WeighbridgeRecord resources, List<MultipartFile> fileList, List<Map<String, Object>> mapList) throws IOException {
if(!ArrayUtil.isEmpty(fileList)){
int size = fileList.size();
if(size > 4){
throw new IllegalArgumentException("上传图片不能超过5张!!!");
}
for(MultipartFile file : fileList) {
if (file.getSize() > 1024 * 1024 * 2) { // 2M
throw new IllegalArgumentException("图片大小不能超过2MB!!!");
}
String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); // 文件名后缀
if (!image.contains(fileSuffix)) {
throw new IllegalArgumentException("格式错误!!!支持" + image + "格式");
}
// 生成图片到本地
this.getPicture(resources.getRecordTime().toString(), mapList, file.getBytes());
}
String jsonStr = JSONUtil.toJsonStr(mapList); // 生成json
resources.setMonitorPicture(jsonStr);
}
}
private void getPicture(String serialNo,List<Map<String, Object>> mapList, byte[] bytes) {
if (null != bytes && bytes.length != 0) {
OutputStream output = null;
BufferedOutputStream bufferedOutput = null;
try {
// 年份
// String year = timePosition.substring(0, 4);
// // 日期
// String date = timePosition.substring(4, 8);
String timePosition = DateUtil.format(new Date(), "yyyyMMdd");
String year = timePosition.substring(0, 4);
// 日期
String date = timePosition.substring(4, 8);
Map<String, Object> map = new HashMap<>();
Long id = IdUtil.nextId();
// 创建文件名
String fileName = "D:\\wwwroot\\mud\\picture\\";
String path = year + "\\" + date + "\\" +serialNo+"_"+id + ".jpg";
File file = new File(fileName + path);
if (!file.exists()) {
FileUtil.touch(file);
}
// 输入的位置
output = new FileOutputStream(file);
bufferedOutput = new BufferedOutputStream(output);
// 二进制 流 写出 图片 保存到本地
bufferedOutput.write(bytes);
map.put("id", id);
map.put("name", id + "");
map.put("path", "picture/" + year + "/" + date + "/" +serialNo+"_"+id + ".jpg");
map.put("size", FileUtilTool.getNetFileSizeDescription(bytes.length));
map.put("suffix", "jpg");
logger.info("========正在插入称重记录图片数据=========",map.toString());
mapList.add(map);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(output != null){
output.close();
}
if(bufferedOutput != null){
bufferedOutput.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
三、遇到的报错
Content type ‘multipart/form-data;boundary=XXXXXXXXXXXXXXXXXX
因为我需要上传多张图片,所以我使用form-data 表单提交的方式进行传参,所以我后端代码是需要使用 @RequestPart 去接收而不是使用@RequestBody 去接收。
如果是没有文件上传,但是需要携带请求参数的话可以是使用@RequestBody,并且用 raw 的json接收
如果后端的请求参数注解和postMan 请求携带参数对应不上就会报这个错。
四、参考博客
本文作者:独而不孤
本文链接:https://www.cnblogs.com/lcaiqin/p/17754826.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步