OpenAPITools / OpenAPITools/openapi-generator

[BUG][typescript-fetch] Multipart/form-data doesnt work with requestBody

Open
#5,112 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Client: TypeScript Issue: Bug
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

Bug Report Checklist
  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • What's the version of OpenAPI Generator used? (openapi-generator-maven-plugin, 4.2.2)
  • Have you search for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Bounty to sponsor the fix (example)
Description

I am trying to upload a file from my TypeScript client using the generated code. However, it seems that the generated code does not place the file blob as body but instead puts it as a url query parameter.

This is the generated method:

postTrack(file, observe = 'body', reportProgress = false) {
    if (file === null || file === undefined) {
        throw new Error('Required parameter file was null or undefined when calling postTrack.');
    }
    let queryParameters = new HttpParams({ encoder: this.encoder });
    if (file !== undefined && file !== null) {
        queryParameters = queryParameters.set('file', file);
    }
    let headers = this.defaultHeaders;
    // to determine the Accept header
    const httpHeaderAccepts = [
        'multipart/form-data'
    ];
    const httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
    if (httpHeaderAcceptSelected !== undefined) {
        headers = headers.set('Accept', httpHeaderAcceptSelected);
    }
    return this.httpClient.post(`${this.configuration.basePath}/api/tracks`, null, {
        params: queryParameters,
        withCredentials: this.configuration.withCredentials,
        headers: headers,
        observe: observe,
        reportProgress: reportProgress
    });
}

whereas this is the Spring endpoint:

@RequestMapping(value = "/tracks", method = RequestMethod.POST)
@ApiResponse(description = "Successful Operation", responseCode = "200", content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE))
public @ResponseBody
String postTrack(
        @RequestParam("file") MultipartFile file
) {
    storageService.store(file);
    return "redirect:/";
}

In my client I am running

const fileBlob = new File([blob], (blob as any).name);
const formData = new FormData();
formData.append('file', fileBlob, fileBlob.name);

this.apiGateway.postTrack(formData, 'events',true)
  .subscribe((event) => {
    if (event.type === HttpEventType.UploadProgress) {
      this.percentDone = Math.round(100 * event.loaded / event.total);
    } else if (event instanceof HttpResponse) {
      this.uploadSuccess = true;
    }
  });

I have tested the endpoint by posting it myself using http: HttpClient:

this.http.post(`${environment.apiBaseUrl}/api/tracks`, formData)
  .subscribe((event) => {
   console.log(event);
});

and it works.

openapi-generator version

I am using the openapi-generator-maven-plugin on version 4.2.2

OpenAPI declaration file content or url
"/api/tracks": {
  "post": {
    "operationId": "postTrack",
    "parameters": [
      {
        "name": "file",
        "in": "query",
        "required": true,
        "schema": {
          "type": "object",
          "properties": {
            "file": {
              "type": "string",
              "format": "binary"
            }
          }
        }
      }
    ],
    "responses": {
      "200": {
        "description": "default response",
        "content": {
          "*/*": {
            "schema": {
              "type": "string"
            }
          }
        }
      }
    }
  }
},
Steps to reproduce

See above.

Suggest a fix

Right now I don't know any better than just posting the data myself instead of using the generated code.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Use the generated TypeScript postTrack method and the supplied OpenAPI declaration as the starting points; compare how the query parameter is interpreted with the intended multipart request. Trace the typescript-fetch generator path that produces this method, then verify that the generated request places the file in the multipart body rather than the URL query.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, typescript
Domain
api, tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.