首页 > 解决方案 > RequestBody 传递的 MultiparFile 为空

问题描述

我正在尝试在 Post 请求中传递文件列表,如下所示:

邮差:

在此处输入图像描述

控制器:

@ApiOperation(value = "Upload documents in the GED")
@PostMapping(consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
@ResponseStatus(code = HttpStatus.CREATED)
public void uploadFileHandler(@ModelAttribute DocumentsUploadForm documentsUploadForm, @RequestBody List<MultipartFile> documents,
        @RequestParam("easy") String easy) throws BusinessException, IOException, CrsPermissionViolationException {
    .... 
    ....
}

所有传递的参数和变量都不为空,只有 MultipartFile 文档的 List 为空。

请问有什么想法吗?

亲切的问候,

标签: springrestpostman

解决方案


此代码适用于来自 POSTMAN 的多个文件。

注意:请注意约定和空值检查。

@PostMapping("/upload")
public void uploadFileHandler(@RequestBody List<MultipartFile> documents, @RequestParam("easy") String easy)
        throws Exception {
    System.out.println(easy);
    if(documents != null && !documents.isEmpty()) {
        for(MultipartFile file : documents) {
            storeFile(file);
        }
    }
}

public void storeFile(MultipartFile file) throws Exception {

    if (!file.isEmpty()) {
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        System.out.println(fileName);
        byte[] bytes = file.getBytes();
        BufferedOutputStream stream = new BufferedOutputStream(
        new FileOutputStream(new File("C://Users//username//Desktop//upload//"+fileName)));
        stream.write(bytes);
        stream.flush();
        stream.close();
    }
}

邮递员请求


推荐阅读