Formidable to formData nodejs nextjs

67 Views Asked by At

I'm try upload image use nextjs and backend use formidable, but to confuse convert the result into formData , using next 13 page.

pages/client.tsx

   const body = new FormData();
        body.append('file', File);
        console.log(body.getAll('file'));
        fetch('/api/upload-image', {
          method: 'POST',
          body,
        })
          .then(res => console.log(res))
          .catch(err => console.log(err));

pages/api/upload-image.tsx

export default async function handler(req: NextApiRequest,res: NextApiResponse){

    const form = new Formidable({ multiples: true });
    const data: Promise<{ fields: formidable.Fields; files: formidable.Files }> =
    new Promise((resolve, reject) => {
      form.parse(req, (error, fields, files) => {
        if (error) reject(error);
        resolve({ fields, files });
      });
    });
    data.then(async ({ fields, files }) => {
      const body = new FormData();
      body.append('file', files);
      try {
        const fetchData = await fetch(`https://example.tco`, {
          method: 'POST',
          body,
          headers: new Headers({
            Authorization: `dfghgjghdgsfa345`,
          }),
        });
        const response = await fetchData.json();
        res.send({ ...response });
      } catch (err) {
        res.status(500).send(err);
      }
    });

}

any solution for this ?

1

There are 1 best solutions below

0
Thành Phong On

I think you should add the 'Content-type' to the req header like this:

 const body = new FormData();
        body.append('file', File);
        console.log(body.getAll('file'));
        fetch('/api/upload-image', {
          method: 'POST',
          body,
          Content-Type:'multipart/form-data',
        })
          .then(res => console.log(res))
          .catch(err => console.log(err));

OR you can try to use axios , like this tutorial: https://www.bezkoder.com/upload-image-react-typescript/

I hope these help you