Skip to content

How to use multipart/form-data in NodeJS? #438

@pedromtcosta

Description

@pedromtcosta

The client gets generated with the createFormData function that is used when the request content is multipart/form-data. The problem is that this function uses the types Blob and File, which are not available in the NodeJS runtime:

protected createFormData(input: Record<string, unknown>): FormData {
  return Object.keys(input || {}).reduce((formData, key) => {
    const property = input[key];
    const propertyContent: any[] = property instanceof Array ? property : [property];

    for (const formItem of propertyContent) {
      const isFileType = formItem instanceof Blob || formItem instanceof File;
      formData.append(key, isFileType ? formItem : this.stringifyFormItem(formItem));
    }

    return formData;
  }, new FormData());
}

using primitiveTypeConstructs to change string.binary from File to Buffer for example does not work for 2 reasons:

  • the createFormData still uses the Blob and File types;
  • the Buffer type lacks some stuff that's needed to upload a file with FormData, such as the file name;

Just as a test, I changed the createFormData function to be like the one below and it worked nicely in an API I am testing with, but this is obviously not a good solution:

const isFileType = formItem instanceof Buffer;
protected createFormData(input: Record<string, unknown>): FormData {
  return Object.keys(input || {}).reduce((formData, key) => {
    const property = input[key];
    const propertyContent: any[] = property instanceof Array ? property : [property];

    for (const formItem of propertyContent) {
      const isFileType = formItem instanceof Buffer;
      if (isFileType) {
        formData.append(key, formItem, {filename: 'any.jpeg'});
      } else {
        formData.append(key, this.stringifyFormItem(formItem));
      }
    }

    return formData;
  }, new FormData());
}

so, is it possible to use multipart/form-data in NodeJS?

Metadata

Metadata

Assignees

Labels

help wantedExtra attention is neededquestionFurther information is requested

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions