Skip to content

File Upload multipart/form-data validation issue #34

@MarcSky

Description

@MarcSky

Good afternoon. Need your help.
I am using openapi: 3.0.0 and github.com/oapi-codegen/nethttp-middleware v1.0.2 library for data validation.
I am trying to upload a photo file to the server but I am facing the following problem.

request body has an error: failed to decode request body: path attachment: unsupported content type \"image/png\”
My swagger file looks like this

  openapi: 3.0.0

  /files/upload:
    post:
      summary: Uploads document
      operationId: uploadFile
      tags:
        - files
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                attachment:
                  type: string
                  format: binary
              required:
                - attachment
            encoding:
              attachment:
                contentType: image/png, image/jpeg
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FileUploadResponse'

I suspect the error occurs github.com/getkin/kin-openapi/openapi3filter/req_resp_decoder.go on line 1462.
we send image contentType = image/png to contentType = multipart/form-data for validation and get an error.

		var value any
		if _, value, err = decodeBody(part, http.Header(part.Header), valueSchema, subEncFn); err != nil {
			if v, ok := err.(*ParseError); ok {
				return nil, &ParseError{path: []any{name}, Cause: v}
			}
			return nil, fmt.Errorf(“part %s: %w”, name, err)
		}

at this point we expect contentType = multipart/form-data but get another one contentType = image/png and return with an error.

	decoder, ok := bodyDecoders[mediaType]
	if !ok {
		return "", nil, &ParseError{
			Kind:   KindUnsupportedFormat,
			Reason: fmt.Sprintf("%s %q", prefixUnsupportedCT, mediaType),
		}
	}

to solve this problem you need to put inside bodyDecoders not only contentType=multipart/form-data but also all contentType and encoding lists (image/png, image/jpeg and so on) in bodyDecoders.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions