Search code examples
javascriptnode.jsaxiosform-data

Send file with form-data and axios


I am trying to send a video to a videosite, I am able to upload the video using the REST api and postman, so I know the api works as intended. Now I want to do exatcly the same request using axios. I have code that looks like the example on how to use form-data and axios:

const form = new FormData();
const stream = fs.createReadStream(PATH_TO_FILE);

form.append('image', stream);

// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
const formHeaders = form.getHeaders();

axios.post('http://example.com', form, {
  headers: {
    ...formHeaders,
  },
})
.then(response => response)
.catch(error => error)

I get the error that data: 'Content-Length is required'

Any ideas?


Solution

  • The solution to my problem was to set Content-Length accordingly:

    "Content-Length": fs.statSync(filePath)['size']