1

I am using PrimeReact 8.5 fileUpload and Next.js 12.3 How do I get just the XML sent from PrimeRact?

I upload the file with

<FileUpload
            name="edcStock"
            url="/api/admin/edcupload"
            onUpload={onUpload}
            accept="text/xml"
            maxFileSize={1000000}
/>

In Next.js API I get the file body with

export default function handler(req:      NextApiRequest, res: NextApiResponse) {
const { body } = req;
console.log(body);
return res.status(200).json({ message: 'called api' });
 }

The body is reported as

------WebKitFormBoundarysugaJxeQVSrDx1AH
Content-Disposition: form-data;    name="edcStock"; filename="edc_xml_en_test.xml"
Content-Type: text/xml

<?xml version="1.0" encoding="UTF-8"?>
<products>
 <product>
   <id>32</id>
juliomalves
  • 42,130
  • 20
  • 150
  • 146

1 Answers1

0

The XML file sent from the FileUpload component is send as form data that you'll need to parse in the API route. Once the body has been parsed, you can then read the data from it and convert the XML to a JavaScript object.

Here's an example that uses formidable for the form data parsing, and fast-xml-parser to convert the XML to JSON.

import fs from 'fs';
import formidable from 'formidable';
import { XMLParser } from 'fast-xml-parser';

const parser = new XMLParser();

// Disable built-in parser so we can handle the body ourselves
export const config = {
    api: {
        bodyParser: false
    }
};

const handler = async (req, res) => {
    const form = new formidable.IncomingForm();

    try {
        // Promisify form parsing so the API route can wait for the parsing to finish
        await new Promise(function (resolve, reject) {
            // Parse form data send in `req.body`
            form.parse(req, async (err, fields, files) => {
                if (err) {
                    reject(err);
                    return;
                }

                // Read parsed data. `edcStock` is the `name` given to the uploaded file
                fs.readFile(files.edcStock.path, function (err, data) {
                    if (err) {
                        reject(err);
                        return;
                    }
                    
                    // Convert XML data to JavaScript object
                    const xmlAsJSON = parser.parse(data);
                    // Handle XML data as you wish
                    console.dir(xmlAsJSON);
                    resolve(xmlAsJSON);
                });
            });
        });

        return res.status(200).json({ response: 'ok' });
    } catch (err) {
        console.error('Error while parsing form', err);
        return res.status(500).json({ error: err });
    }
};

export default handler;
juliomalves
  • 42,130
  • 20
  • 150
  • 146