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();
                }
            }
        }
    }

image

三、遇到的报错

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

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

四、参考博客

https://zhuanlan.zhihu.com/p/585706264?utm_id=0

posted @ 2023-10-10 15:34  林财钦  阅读(1183)  评论(0)    收藏  举报