我正在尝试构建一个next.js应用程序,它接受multipart/form-data,然后从一个端点接收它,该端点将formdata解析为名称,地址和文件。
我尝试使用Formidable来解析formdata对象,但一直在努力让它工作。字段和文件都返回{} {}。(空)。对于如何解析表单数据有什么建议吗?
export default function supplier(req, res) {
if (req.method == 'POST') {
//console.log("req: \n",req);
console.log("req body: \n",req.body);
//console.log("req.file: \n",req.headers);
//console.log("req.address: \n",req.body.address);
const form = new formidable.IncomingForm();
//console.log("form: \n",form);
//const form = new multiparty.Form();
let FormResp = new Promise((resolve,reject)=>{
form.parse(req, (err, fields, files)=>{
console.log("fields: ",fields);
console.log("files: ",files);
//await saveFile(files.file);
//await saveDB();
return res.status(201).send("");
});
});
} else {
// Handle any other HTTP method
return res.status(405).json({ error: `Method '${req.method}' Not Allowed` });
}
const handleSubmit = async (event) => {
event.preventDefault();
const formdata = new FormData();
const json = JSON.stringify({"name":event.target.name.value, "address":event.target.address.value, "file": createObjectURL})
formdata.append("file", image);
formdata.append("name", event.target.name.value);
formdata.append("address", event.target.address.value);
console.log("formdata: \n", formdata);
//var request = new XMLHttpRequest();
//request.open("POST", "/api/supplier");
//request.send(formData:body);
const response = await fetch("/api/supplier",{method: 'POST', body: formdata, "content-type":"multipart/form-data"});
//const result = await response.json()
//console.log(result)
};
------WebKitFormBoundaryiu8apU5i3hWyORTY
Content-Disposition: form-data; name="name"
Hello
------WebKitFormBoundaryiu8apU5i3hWyORTY
Content-Disposition: form-data; name="address"
addressssssssss
------WebKitFormBoundaryiu8apU5i3hWyORTY--
req body:
------WebKitFormBoundary92WJpSOKb0mEfOAH
Content-Disposition: form-data; name="file"; filename="attachment.svg"
Content-Type: image/svg+xml
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 48 48" viewBox="0 0 48 48"><path d="M35.5,34V16c0-0.83-0.67-1.5-1.5-1.5s-1.5,0.67-1.5,1.5v18c0,4.69-3.81,8.5-8.5,8.5s-8.5-3.81-8.5-8.5V11
c0-3.03,2.47-5.5,5.5-5.5s5.5,2.47,5.5,5.5v21.5c0,1.38-1.12,2.5-2.5,2.5s-2.5-1.12-2.5-2.5V13c0-0.83-0.67-1.5-1.5-1.5
s-1.5,0.67-1.5,1.5v19.5c0,3.03,2.47,5.5,5.5,5.5s5.5-2.47,5.5-5.5V11c0-4.69-3.81-8.5-8.5-8.5s-8.5,3.81-8.5,8.5v23
c0,6.34,5.16,11.5,11.5,11.5S35.5,40.34,35.5,34z"/></svg>
------WebKitFormBoundary92WJpSOKb0mEfOAH
1条答案
按热度按时间pw9qyyiw1#
你是说你的标题中的
multipart/form-data
吗?在Next.js中使用强大的解决方案是禁用内置的body解析器。这可以通过从API路由导出一个配置对象并将api.bodyParser设置为false来完成。这将使请求流保持不变,以便强大可以解析它。
只需添加以下行: