Проблема с MultipartFile в ответе OpenAPI 3.0 - PullRequest
0 голосов
/ 12 марта 2020

Я реализую интерфейс REST с GET, который должен возвращать файл Multipart. Но все, что доступно через OPEN API, это

      responses:
        200:
         description: Requested Document
         content:
          application/pdf:
            schema:
              type: string
              format: binary
          image/png:
            schema:
              type: string
              format: binary
          multipart/form-data:
            schema:
              type: string
              format: binary

Это преобразуется в нижеприведенное, когда я строю через генератор OPEN API, плагин 3.3.4

    @ApiOperation(value = "Returns a Document object for the given groupId", nickname = "getDocumentForDocumentId", notes = "Returns all Document objects for the given groupId", response = Resource.class, tags={ "DocumentUpload", })
    @ApiResponses(value = { 
        @ApiResponse(code = 200, message = "Requested Document", response = Resource.class),
        @ApiResponse(code = 400, message = "Invalid Request"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 404, message = "Not Found"),
        @ApiResponse(code = 500, message = "Internal Server Error") })
    @RequestMapping(value = "/documentupload/v1/{groupId}",
        produces = { "application/pdf", "image/png", "multipart/form-data" }, 
        method = RequestMethod.GET)
    default ResponseEntity<Resource> getDocumentForDocumentId(@ApiParam(value = "The Unique ID to search your documents",required=true) @PathVariable("groupId") String groupId,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "documentId", required = true) String documentId,@ApiParam(value = "" ,required=true) @RequestHeader(value="sourceSystemId", required=true) String sourceSystemId,@ApiParam(value = "") @Valid @RequestParam(value = "objectName", required = false) String objectName) {
        return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
    }

Если вы видите, я получаю ответ = Resource.class и производит разделы показывает, что производит = {"application / pdf", "image / png", "multipart / form-data"}

Таким образом, все, что я могу послать, это только ресурсный поток и не Multipart (info + binary)

Вопрос: Есть ли способ настроить открытый API-интерфейс так, чтобы я получал Multipart в качестве класса ответа в моих сгенерированных классах контроллеров?

Если я попытаюсь написать функцию с ответом = CommonsMultipartFile.class и удалить приводит к {= application / pdf "," image / png "," multipart / form-data "}, я получу следующее исключение

{"timestamp":"2020-03-12T12:46:22.104+0000","status":200,"error":"OK","message":"Type definition error: [simple type, class java.io.FileDescriptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.web.multipart.commons.CommonsMultipartFile[\"fileItem\"]->org.apache.commons.fileupload.disk.DiskFileItem[\"inputStream\"]->java.io.FileInputStream[\"fd\"])","path":"/document-upload/documentupload/v2/u7677"}

Я использовал приведенный ниже код для преобразования объекта AWS S3, поступающего из бэкэнда, в Multipartfile, который затем отправляется в ответ на REST API

S3ObjectInputStream objectInputStream = s3Object.getObjectContent();
FileItem fileItem = new DiskFileItemFactory().createItem("file",
                        s3Object.getObjectMetadata().getContentType(), false, fileName);

                try (InputStream in = objectInputStream; OutputStream out = fileItem.getOutputStream()) {
                    in.transferTo(out);
                } catch (Exception e) {
                    throw new IllegalArgumentException("Invalid file: " + e, e);
                }

                MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...