Send File as Body

36 views Asked by At

I want to use speech to text API of open ai in my Next.js app. As don't have separate server i am using the code for api

// pages/api/audiototext.ts
import { NextApiRequest,NextApiResponse } from "next";
export const config = {
  api: {
    bodyParser: false,
  },
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try{
    fetch('https://api.openai.com/v1/audio/transcriptions',{
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.NEXT_PUBLIC_OPENAI_API_KEY}`,
      },
      body:req.body
    })
    .then(response => response.json())
    .then(data => {
      console.log(data)
      res.status(200).json(data)
    })
    .catch((error) => {
      res.status(500).json({error:error})
    })
  }
  catch(error){
    res.status(500).json({error:error})
  }
}

and on client side the code is

const formData = new FormData();
    formData.append('file', audioFileU);
    formData.append('model', 'whisper-1');
    const response = await fetch(`/api/audiototext`, {
      method: 'POST',
      body: formData, // Do not set Content-Type here
    });

I am getting too many errors.

I tried Formidable and multer in both i am getting errors like sometime on server i am getting Boundary not found error during parsing sometimes i am getting error through open ai that Could not parse multipart form

0

There are 0 answers