0

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?

user4157124
  • 2,809
  • 13
  • 27
  • 42
Hugo
  • 135
  • 2
  • 9

3 Answers3

2

May be I got your questions wrong , you want to add Content-Length in the header. I can see you are uploading video stream. So first you have to calculate the data chunk length.

('Content-Length', File.getSize(stream)) Reference: Can I stream a file upload to S3 without a content-length header?

You can make the post request as multi-part type : 'Content-Type': 'multipart/form-data'. It is preferable way to send large data to server. You can check this link : How do I set multipart in axios with react?

If I got your question wrong , plese comment or reply . Thanks

subhadip pahari
  • 799
  • 1
  • 7
  • 16
  • Thanks! Your comment helped me find the solution! See below for the solution: `Content-Length": fs.statSync(filePath)['size']` – Hugo Jul 24 '20 at 22:21
1

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

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

Hugo
  • 135
  • 2
  • 9
0

I think the best way to handle this is to actually use the FormData's own method:

const headers = { 'content-length': formData.getLengthSync(), ...formData.getHeaders() }

This will be more accurate because it includes any other data you may add.

To expound, if you are using a ReadStream, you must use the async function instead.

const { promisify } = require('util')

const getLength = promisify(formData.getLength.bind(formData))
const contentLength = await getLength()
const headers = { 'content-length': contentLength, ...formData.getHeaders() }
Craig O'Connor
  • 153
  • 3
  • 10