首页 > 解决方案 > 无法在 rest api 中使用 InputStream 上传多个文件

问题描述

我想使用spring在rest api中上传多个文件。我可以使用以下代码上传单个文件

    @Path("/line-item/cancel")
    @Produces({"application/xml", "application/json"})
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    @ApiOperation(value = "Api to cancel PO Line Items", response = POLineItemCancellationResponse.class)
    POLineItemCancellationResponse cancelPoLineItems(@Multipart(value = "data") String poLineItemCancellationRequestEntry, @Multipart(value="file") InputStream inputStream);

但是如果我尝试输入,@Multipart(value="file") InputStream[] inputStream那么我会在输入流中得到空对象。

我也尝试过使用 MultiPartFile

POLineItemCancellationResponse cancelPoLineItem(@RequestPart(value="file") MultipartFile[] files);

但我收到以下错误:

No message body reader has been found for class [Lorg.springframework.web.multipart.MultipartFile;

标签: javaspringrestmultipart

解决方案


我已经用我的休息电话来上传多个文件,例如(未尝试使用 srping)

@FormDataParam("file") FormDataContentDisposition fileDisposition,
            @FormDataParam("file") List<FormDataBodyPart> bodyParts

这是大摇大摆的定义

@ApiImplicitParam(name = "file", value = "One or more files", allowMultiple = true, required = true, dataType = "file", paramType = "form")



for (int i = 0; i < bodyParts.size(); i++) {
            // * Casting FormDataBodyPart to BodyPartEntity, which can give us
            // * InputStream for uploaded file
            BodyPartEntity bodyPartEntity = (BodyPartEntity) bodyParts.get(i)
                    .getEntity();
            fileDisposition = bodyParts.get(i).getFormDataContentDisposition();
            try { 
                  String fileName = URLEncoder.encode(
                FilenameUtils.getName(fileDisposition.getFileName()), "UTF-8");
        String documentFormat = fileName
                .substring(fileName.lastIndexOf(".") + 1);
        InputStream file = bodyPartEntity.getInputStream();
}

在这里,您将获得您正在寻找的输入流列表。


推荐阅读