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.
for those who are still looking for a solution on how to use multer as middleware with nextJs, here is an example of an API route, using multer has middleware. The route is calling a getSignedUrl function to upload file to bucket.
running nextJs v12 and multer 1.4.3
import multer from "multer";
import { NextApiRequest, NextApiResponse } from "next";
import { getSignedUrl } from "../../lib/uploadingToBucket";
function runMiddleware(
req: NextApiRequest & { [key: string]: any },
res: NextApiResponse,
fn: (...args: any[]) => void
): Promise<any> {
return new Promise((resolve, reject) => {
fn(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
export const config = {
api: {
bodyParser: false,
},
};
const handler = async (
req: NextApiRequest & { [key: string]: any },
res: NextApiResponse
): Promise<void> => {
//const multerStorage = multer.memoryStorage();
const multerUpload = multer({ dest: "uploads/" });
await runMiddleware(req, res, multerUpload.single("file"));
const file = req.file;
const others = req.body;
const signedUrl = await getSignedUrl(others.bucketName, file.filename);
res.status(200).json({ getSignedUrl: signedUrl });
};
export default handler;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With