'My nextjs form returns undefined on api part on file upload?
I have a multipart form and i have created a route inside api, i am using some packages to handle file upload but i get undefined whenever i try to print form data inside the api middleware
I have tried tweaking a lot with the code but the online soutions just doesnt work need a better way to do it
here is the code for formmiddleware
import nextConnect from "next-connect";
import multiparty from "multiparty";
const middleware = nextConnect();
middleware.use(async (req, res, next) => {
const form = new multiparty.Form();
await form.parse(req, function (err, fields, files) {
req.body = fields;
req.files = files;
console.log(fields, " files ", files);
next();
});
});
export default middleware;
code for api route
import formParserMiddleware from "../../../middlewares/formParser";
import nextConnect from "next-connect";
const handler = nextConnect();
handler.use(formParserMiddleware);
handler.post(async (req, res) => {
res.json({ files: req.files, body: req.body });
});
export default handler;
code for form
<form
method="POST"
action="/api/book/upload"
encType="multipart/form-data"
>
<label htmlFor="UploadBook__title" className={styles.UploadBook__label}>
Title of book
</label>
<input placeholder="title here" name="title" id="UploadBook__title" />{" "}
<br />
<label
htmlFor="UploadBook__author"
className={styles.UploadBook__label}
>
Author
</label>
<input placeholder="Author" name="author" id="UploadBook__author" />{" "}
<br />
<label htmlFor="UploadBook__pdf" className={styles.UploadBook__label}>
PDF Book (if available)
</label>
<input placeholder="pdf" name="pdf" id="UploadBook__pdf" type="file" />{" "}
<br />
<label htmlFor="UploadBook__audio" className={styles.UploadBook__label}>
PDF Book (if available)
</label>
<input
placeholder="audio files"
id="UploadBook__audio"
name="audio"
type="file"
multiple
/>{" "}
<br />
<label htmlFor="UploadBook__desc" className={styles.UploadBook__label}>
Description of book
</label>
<input
placeholder="Description"
name="description"
id="UploadBook__desc"
/>{" "}
<br />
<h1>Product Details</h1>
<div>
<span>Price</span>{" "}
<input placeholder="if you wanna sell(rs)" name="price" /> <br />
<span>Publisher</span>{" "}
<input placeholder="publisher" name="publisher" /> <br />
<span>Publish Date</span>{" "}
<input placeholder="date of publishing" type="date" name="date" />{" "}
<br />
<span>Pages</span>{" "}
<input placeholder="total pages" name="total pages" /> <br />
<span>Dimensions</span>{" "}
<input placeholder="total page size" name="page size" /> <br />
</div>
<button type="submit">Submit</button>
</form>
the console.log() in middleware is printing undefined also the result is empty
I tried file and formdata uploading but got undefined
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
