How can I pass my csv file as Form Data using REST API

I'm having a hard time on encoding my uploaded CSV file to Form Data, This is the idea I came up with to be able to pass the actual file to be processed on the backend using post method of my API. But unfortunately, I'm getting an error "TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.". I am new to programming so I hope you understand. Thank you!

Here is some snippet of what I've done:

uploadedProducts contains the csv file I uploaded.

        upload() {
          let data = new FormData(self.uploadedProducts);
          
          axios.post(`${api}/mc/upload/specifications`, {
              data,
              headers: {
                'Content-Type': 'multipart/form-data'
              }
          })
          .then((result) => {
              let responseData = result.data
              alert("Uploaded successfully!")     
          })
          .catch((error) => {
              self.showErrorMessage(error.message);
          })
        }

1 answer

  • answered 2020-07-14 08:13 User 28

    var formData = new FormData(form)
    

    The form must be an HTML element. Please read FormData(). From your errors I guess your self.uploadedProducts is not a form element.

    The alternative is use append method. Please read FormData.append().

    So your code should be something like:

    upload() {
        let data = new FormData();
        data.append('fieldName', self.uploadedProducts);
        ...
        // you can omit multipart/form-data header
        axios.post(`${api}/mc/upload/specifications`, data)
        ...
    }