springBoot 同时上传多张图片且携带请求参数

发布时间 2023-10-10 15:36:23作者: 林财钦

一、背景

需要同时上传多张图片,同时需要携带请求参数

二、实现

点击查看代码
@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);

        }
    }

image

三、遇到的报错

Content type ‘multipart/form-data;boundary=XXXXXXXXXXXXXXXXXX
因为我需要上传多张图片,所以我使用form-data 表单提交的方式进行传参,所以我后端代码是需要使用 @RequestPart 去接收而不是使用@RequestBody 去接收。
image
如果是没有文件上传,但是需要携带请求参数的话可以是使用@RequestBody,并且用 raw 的json接收
image

如果后端的请求参数注解和postMan 请求携带参数对应不上就会报这个错。

四、参考博客