1

I want to read the CSV file from Next.js API and it's sent from POSTMAN like the below image

enter image description here

But how do I read that CSV file?

Like this below code, I don't read the file anyhow.

export default async function handler(req, res) {
     console.log(req.body);
     // console.log(req.file); // Undefined
     // console.log(req.files['file']); // Undefined
}

My goal is to read files and convert them to an array of data.

Thanks

user9769384
  • 70
  • 1
  • 18
  • Does this answer your question https://stackoverflow.com/questions/23114374/file-uploading-with-express-4-0-req-files-undefined – derpirscher Nov 23 '22 at 11:49

1 Answers1

0

I recommend you to use the formidable package to read the files server side. You also need to disable bodyParser. A minimum example would be this code:

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
) {
    if (req.method === "POST") {
        const data: {fields, files} = await new Promise((resolve, reject) => {
            const form = new IncomingForm();
            form.parse(req, (err, fields, files) => {
                if (err) return reject(err);
                resolve({ fields, files });
            });
        });
        const file = data.files.file;
        let fileData = await fs.promises.readFile(file.filepath);
        
        // now you need to parse the csv file (contents is in the fileData buffer) or do what ever you want

        res.status(200).end("Uploaded");
        return;
    }

    res.status(400).end("Method not allowed");
}

export const config = {
    api: {
        bodyParser: false,
    }
};

A package for parsing csv files can be found here

Fatorice
  • 515
  • 3
  • 12