如何在Next.js API路由中从主体读取XML



我使用的是PrimeAreact 8.5文件Upload和Next.js 12.3如何只获取PrimeRact发送的XML?

我用上传文件

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

在Next.js API中,我获得了带有的文件主体

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

尸体被报告为

------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>

FileUpload组件发送的XML文件将作为表单数据发送,您需要在API路由中解析该表单数据。一旦解析了主体,就可以从中读取数据,并将XML转换为JavaScript对象。

下面的示例使用formidable进行表单数据解析,使用fast-xml-parser将XML转换为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;

相关内容

  • 没有找到相关文章