Search code examples
javascriptnode.jsfileform-data

Send image file in FormData node JS ends with error


This is my function in my node JS script:

const uploadFile = async () => {
  const buffer = fs.readFileSync('scripts/pose.png')
  const formData = new FormData()

  formData.append('file', buffer, 'dummyName.png')

  const headers = {
    Authorization: `Bearer ${jwt}`,
    maxBodyLength: Infinity,
    maxContentLength: Infinity,
  }

  const response = await axios.post(
    `${process.env.URL}/v1/files`,
    formData,
    {
      headers
    },
  )

  return response
}

no matter what I'm doing it's not working... with this code I'm getting an error: "source.on is not a function"

Can someone help me, I tried literally everything!


Solution

  • const uploadFile = async () => {
      const buffer = fs.readFileSync(
        'scripts/pose.png',
      );
      const formData = new FormData();
    
      formData.append('file', buffer, {
        filename: 'dummyName.png',
        contentType: 'image/jpeg', // Adjust the content type accordingly
      });
    
      const headers = {
        Authorization: `Bearer ${jwt}`,
        'Content-Type': 'multipart/form-data',
        ...formData.getHeaders(),
      };
    
      const response = await axios.post(`${process.env.URL}/v1/files`, formData, {
        headers,
      });
    
      return response;
    };