Ошибка HTTP 415: Неподдерживаемый тип носителя с сервисом, созданным с помощью генератора OpenApiJAVA

Программисты JAVA общаются здесь
Ответить
Гость
 Ошибка HTTP 415: Неподдерживаемый тип носителя с сервисом, созданным с помощью генератора OpenApi

Сообщение Гость »


Я использую openapi-generator-cli (

Код: Выделить всё

"@openapitools/openapi-generator-cli": "^2.9.0"
) in an Angular project to generate all services from a Java API.
It works great in most of the cases, but I struggle to make it works for a file upload. I always get an HTTP error 415 Unsupported Media Type

Java (Spring boot) endpoint looks like this

Код: Выделить всё

    @PostMapping(value = "file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void importFile(@RequestParam("file") MultipartFile file) {
this.importController.importFile(file);
}
Open api descriptor from this endpoint looks like this

Код: Выделить всё

    "requestBody": {
"content": {
"multipart/form-data": {
"schema": {
"required": ["file"],
"type": "object",
"properties": { "file": { "type": "string", "format": "binary" } }
}
}
}
},
Generated service code in Angular looks like this

Код: Выделить всё

public importFile(
file: Blob,
observe: any = 'body',
reportProgress: boolean = false,
options?: { httpHeaderAccept?: undefined; context?: HttpContext }
): Observable {
if (file === null || file === undefined) {
throw new Error('Required parameter file was null or undefined when calling importFile.');
}

// some code about HTTP Headers
// some code about HttpContext

// theses variables seem to be unused !
const consumes: string[] = ['multipart/form-data'];
const canConsumeForm = this.canConsumeForm(consumes);

let localVarFormParams: { append(param: string, value: any): any };
let localVarUseForm = false; // always false
let localVarConvertFormParamsToString = false; // always false
if (localVarUseForm) {
localVarFormParams = new FormData();
} else {
// always pass here
localVarFormParams = new HttpParams({ encoder: this.encoder });
}

// some code about response type

return this.httpClient.post(
`${this.configuration.basePath}/api/priv/imports/file`,
localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams,
{
context: localVarHttpContext,
responseType: responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}

If I manually call the Java endpoint with the following code, it works perfectly

Код: Выделить всё

const formData: FormData = new FormData();
formData.append('file', file);
this.httpClient.post(`${this.configuration.basePath}/api/priv/imports/file`, formData)
But if I call the service generated by OpenApi, then I get the

Код: Выделить всё

HTTP error 415 Unsupported Media Type
:

Код: Выделить всё

const formData: FormData = new FormData();
formData.append('file', file);
this.importResourceService.importFile(formData as any)
I noticed that in the generated service code, some variables are unused or always false,

Код: Выделить всё

localVarFormParams
does not even contains the file.

If I just replace

Код: Выделить всё

localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams
by then it works but I do not want to update the generated code manually !

So I wonder what I could change to make OpenApi to generate a working code to upload file on server.


Источник: https://stackoverflow.com/questions/781 ... api-genera
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»