Как я могу указать многочастную загрузку файла с параметрами - PullRequest
1 голос
/ 04 июля 2019

Я пытаюсь задокументировать метод API, который получит файл и два параметра как int. С помощью редактора Swagger я смог описать то, что я хочу, но не смог воспроизвести это, используя аннотации.

what I want

Это то, что я рисую в редакторе Swagger

requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                flow:
                  type: integer
                environment:
                  type: integer
                file:
                  type: string
                  format: binary
        required: true

Если я использую consumes = MediaType.MULTIPART_FORM_DATA, я получу параметры. И если я использую consumes = MediaType.APPLICATION_OCTET_STREAM, я получаю файл для загрузки.

failed attemp 1 failed attemp 2

@Operation(summary = "Unpack Files",
            description = "Receives a packed zip or gzip file with xml files inside or receives xml files",
            security = @SecurityRequirement(name = "apiKey"),
            responses = {
                    @ApiResponse(responseCode = "201", description = "Created"),
                    @ApiResponse(responseCode = "400", description = "Something Went Wrong"),
                    @ApiResponse(responseCode = "401", description = "Unauthorized"),
                    @ApiResponse(responseCode = "503", description = "Service Unavailable")
            },
            requestBody = @RequestBody(
                content = @Content(
                    mediaType = MediaType.MULTIPART_FORM_DATA,
                    schema = @Schema(implementation = Document.class, format = "binary"),
                    encoding = @Encoding(
                            name = "file",
                            contentType = "application/xml, application/zip, application/gzip"
                    )
                ),
                required = true
            )
    )
    @Post(value = "/unpack", consumes = MediaType.APPLICATION_OCTET_STREAM)
    public Single<HttpResponse<String>> upload(StreamingFileUpload file, int flow, int environment) throws IOException {
        return Single.just(new Document(file.getFilename(), environment, flow))
            .flatMap(DocumentValidation::validateDocumentExtension)
            .doOnError(throwable -> {
                log.error("Validation exception: {}", throwable.getMessage());
                exception = throwable.getMessage();
            })
            .doOnSuccess(doc -> {
                log.info("File saved successfuly");
                File tempFile = File.createTempFile(file.getFilename(), "temp");
                file.transferTo(tempFile);
            })
            .map(success -> {
                if (exception != null || !exception.equals("")) {
                    return HttpResponse.<String>status(HttpStatus.CREATED).body("Uploaded");
                } else {
                    return HttpResponse.<String>status(HttpStatus.SERVICE_UNAVAILABLE).body(exception);
                }
            }
        );
    }

Заранее спасибо.

1 Ответ

0 голосов
/ 05 июля 2019

Выглядит как пропавший без вести @QueryValue

Из документации 6.4 Простая привязка запроса :

Привязки из переменной URI запроса или параметра запроса | @QueryValue String myParam

Из документации 6.19. Загрузка файлов :

Метод настроен на использование MULTIPART_FORM_DATA

Параметры метода соответствуют именам атрибутов формы. В этом случае файл будет соответствовать, например,

Метод StreamingFileUpload.transferTo (java.lang.String) используется для передачи файла на сервер.

Kotlin просто:

@Controller
class SomeController {

    @Post(value = "/", consumes = [MediaType.MULTIPART_FORM_DATA])
    fun upload(file: StreamingFileUpload,
               @QueryValue flow: Int,
               @QueryValue environment: Int): Single<HttpResponse<String>> {
        val tempFile = File.createTempFile(file.filename, "temp")
        return Single.fromPublisher(file.transferTo(tempFile))
                .map { success ->
                    if (success) {
                        HttpResponse.ok("Uploaded");
                    } else {
                        HttpResponse.status<String>(HttpStatus.CONFLICT)
                                .body("Upload Failed")
                    }
                }
    }

}
...