reactjstypescriptmultipartform-data

JavaScript typescript formData append empty Array


I have a multi select input. If ı select any option and send not problem. When not select any value. then send form with empty array. But formData not accept to [].

let formData = new FormData();
formData.append('education_level', []); //not accept

Solution

  • The append method only accepts strings or Blob objects (including File objects).

    FormData is for use when you're going to provide multipart/form-data. There's no concept of an empty array in multipart/form-data, you just don't include any values for the key at all, and the server should infer that that means any "array" of values it was expecting is empty.

    For completeness: If you did have an array of values, you wouldn't do .append("theKey", theArray); instead, you'd append them like this:

    for (const value of theArray) {
        data.append("theKey", value);
    }
    

    All of the values will be included in the result.