0

I have a fairly simple Axios post which has a file and a few fields in a JSON string.

Here is the working Curl from postman:

curl --location --request POST 'http://localhost:8080/v1/uploadData’ \
--form 'file=@"/Users/guy/a_file.xlsx"' \
--form 'uploadDetails="{\"clientId\": 2, \"userId\": \"1\", \"fileName\": \"filename8\", \"effectiveDate\": \"04-01-2021\"}";type=application/json'

This is the code in js (vue):

    uploadFile(files) {
      const formData = new FormData();
      const file = files[0];
      const uploadDetails = JSON.stringify(
        {
          clientId: 2,
          userId: 1,
          fileName: file.name,
          effectiveDate: this.effectiveDate,
        },
      );
      formData.append('uploadDetails', uploadDetails);
      formData.append('file', file);
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      };
      const uploadApi = `http://${process.env.FILE_UPLOAD_API}/v1/uploadData`;
      const response = axios.post(
        uploadApi,
        formData,
        config,
      ).then(() => {
        console.log('SUCCESS!!');
      })

The Curl post works just fine! However, when I try to run this Axios POST, the following happens in the logs of my java back end (Spring Webflux).

Parsed parts [file, uploadDetails] (content masked)
Decoding part 'uploadDetails'
No Content-Type, using application/octet-stream
Could not resolve parameter [1] in public
Completed 415 UNSUPPORTED_MEDIA_TYPE

I am assuming that it has to do with the ;type=application/json on the JSON object, but I can't seem to see how to tell Axios to put that on the uploadDetails bit. Does anyone else know how?

Beatscribe
  • 423
  • 8
  • 17
  • [This question and answer](https://stackoverflow.com/questions/24535189/composing-multipart-form-data-with-a-different-content-type-on-each-parts-with-j/24535293#24535293) basically worked for me. – Beatscribe Mar 19 '21 at 02:46

1 Answers1

0

This post basically answers my question. To tell it that the json part of my form data is json I have to convert it to a blob which allows me to set the content-type for each part.

formData.append(
        'uploadDetails',
        new Blob([uploadDetails],
          { type: 'application/json' }),
      );
Beatscribe
  • 423
  • 8
  • 17