1

I am trying to submit to FastAPI using NextJS API.

  const file = e.target.files[0];
  const formData = new FormData();
  formData.append("file", file);
  fetchClient(hendlerData, { "Content-Type": "multipart/form-data" }).post(formData);

If on NextJS API

async function hendler(req: NextApiRequest, res: NextApiResponse<SessionUser>) {
  if(req.method === "POST"){
    const response = fetch(endPoint, {
      method: "POST",
      headers: { "Content-Type": req.headers["content-type"] },
      body: req.body,
    });
  }

}

Then the file is saved via FastAPI in the format application/octet-stream. If you load it after that, it will be something like this.

HEADERS 
server: [ 'nginx/1.18.0 (Ubuntu)' ],
date: [ '' ],
'content-type': [ 'application/octet-stream' ],
'content-length': [ '92556' ],
connection: [ 'keep-alive' ],
'content-disposition': [ 'inline; filename="photo.bin"' ]

If using formidable

import { IncomingForm } from "formidable";
export const config = {
 api: {
  bodyParser: false,
 },
};
....
async function hendler(req, res: NextApiResponse) {
  const data: any = await new Promise((resolve, reject) => {
      const form = new IncomingForm();

      form.parse(req, (err, fields, files) => {
        if (err) return reject(err);
        resolve({ fields, files });
      });
 });

 // console.log(data)
fields: {},
files: 
 file: PersistentFile 
   _events: [Object: null prototype],
   _eventsCount: 1,
   _maxListeners: undefined,
   lastModifiedDate: #########,
   filepath:'/var/folders/qx/....',
   newFilename: '15c946ac557fb54e369e94f00',
   originalFilename: ###########,
   mimetype: 'image/jpeg',
   hashAlgorithm: false,
   size: 51374,
   _writeStream: [WriteStream],
   hash: null,


 const response = fetch(endPoint, {
      method: "POST",
      headers: { "Content-Type": req.headers["content-type"] },
      body: ??????,   // req.body undefined 
 });
}

}

 ...

What to send to the body?

  • What are you trying to do ? – Walle Cyril Oct 07 '22 at 13:25
  • Please have a look at related answers [here](https://stackoverflow.com/a/73264904/17865804), [here](https://stackoverflow.com/a/70689003/17865804) and [here](https://stackoverflow.com/a/70640522/17865804). Additionally, make sure to let the browser set the `Content-Type` header along with the `boundary` string used to separate each body part in the `multipart` payload (take a look at [this answer](https://stackoverflow.com/a/71711008/17865804) and [this answer](https://stackoverflow.com/a/70641755/17865804) for more details). – Chris Dec 27 '22 at 09:46

0 Answers0