0

I tried the following from Node.js:

import axios from 'axios';

const axiosInstance = axios.create({});

(async () => {
    const sendData = new FormData();
    sendData.append('firmware', 'hello');

    const result = await axiosInstance({
        data: sendData,
        headers: { 'content-type': 'multipart/form-data' },
        method: 'PUT',
        url: 'http://localhost',
    });

    console.log(result);
})().catch(console.error);

But I got this error when calling send:

AxiosError: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream

I am using axios version ^0.27.2. I tried various ways of stringifying the data, but I kept getting this error. I also tried using the form-data package, but its API does not match the actual FormData API and the data would not actually get sent.

How can I properly send my file as part of a FormData object to my endpoint?

4
  • 2
    [email protected] is from April 2022. Is there a reason why you need to use such an old version? Commented Jul 28 at 18:12
  • See github.com/axios/axios/issues/4710 Commented Jul 28 at 18:43
  • @robertklep I didn't realize it was old. I will try the latest version. Commented Jul 28 at 18:59
  • @RuanMendes I have read that thread up and down, but the solution there was just to construct the object differently, which does not work. I'll see if the newer version fixes the problem. Commented Jul 28 at 19:00

2 Answers 2

1

Using form-data package, try:

const result = await axiosInstance({
    data: sendData.getBuffer(),
    headers: sendData.getHeaders(),
    method: 'PUT',
    url: 'http://localhost',
});

see:

Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data.

axios.post('https://example.com/path/to/api', form.getBuffer(), form.getHeaders());

Note: Because the output is of type Buffer, you can only append types that are accepted by Buffer: string, Buffer, ArrayBuffer, Array, or Array-like Object. A ReadStream for example will result in an error.

Buffer getBuffer()

Sign up to request clarification or add additional context in comments.

2 Comments

getBuffer() is not an instance method for FormData. It appears this is something made up by the form-data package.
@nullromo true, but they don't claim to be spec compliant..
0

As @robertklep pointed out, my axios version was old. Updating to the latest (currently ^1.11.0) solved my problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.