DebugFactor.com | Forum

How to submit a multipart/form-data with a file and text field to server (API) in React JS?

I want to upload a file along with a text field to an API (API created on top of an AWS Lambda function with API Gateway) with ReactJS.
Is there any reliable library to achieve this? Also how to parse the data in the API side?

To submit a file and a text value to the server you have to use multipart form data. In React, you create a new form data as

const formData = new FormData();

Now to add data to the form data,

var files = document.getElementById("labReportFile").files;
var file = files[0];
var fileName = file.name;

formData.append(
  "labReportFile",
  file,
  fileName
);
      	
var field1Value= document.getElementById("field1").value;
formData.append(
  "field1",
  field1Value
);

var field2Value= document.getElementById("field2").value;
formData.append(
  "field2",
  field2Value
);

const config = {
  headers: {
     'content-type': 'multipart/form-data'
  }
};

axios.post(url, formData, config)
  .then(function(){
      console.log("Success");
 })
 .catch(function(error){
      console.log(error);
});