I'm using nextjs and I want to upload a file so I used next-connect in order to use multer
import nc from "next-connect";
import multer from "multer";
export const config = {
api: {
bodyParser: false,
},
}
const upload = multer({ dest: `${__dirname}../../public` });
const handler = nc()
.use(upload.single('image'))
.post(async (req, res)=>{
console.log(req.body); // undefined
console.log(req.file); // undefined
res.status(200).send("yo");
})
export default handler;
this is the client side code :
function handleOnSubmit(e){
e.preventDefault();
const data = {};
var formData = new FormData(e.target);
for (const [name,value] of formData) {
data[name] = value;
}
data.type = data.type[0].toUpperCase();
data.name = data.name[0].toUpperCase();
axios({
method: "POST",
url:"/api/manager",
data,
config: {
headers: {
'content-type': 'multipart/form-data'
}
}
})
.then(res=>{
console.log(res);
})
.catch(err=>{
throw err
});
}
...
return(
...
<Form onSubmit={(e)=>handleOnSubmit(e)}>
...
</Form>
)
I searched and everything I found was related to nodejs and expressjs but nothing on next.js. I have no idea about how to proceed.
When I switched to the Next.js framework, I first tried to upload a file with the 'multer' library and preferred to give up and use 'formidable'. The reason was that there were a few resources available with Nextjs and multer.
And if I'm not wrong here, multer should be added as middleware, so this means rewriting the server.js page. You can review these topics:
If you don't want to deal with this, you can check out a simple gist on using this resource formidable library: https://gist.github.com/agmm/da47a027f3d73870020a5102388dd820
And this is the file upload script I created: https://github.com/fatiiates/rest-w-nextjs/blob/main/src/assets/lib/user/file/upload.ts