I am creating a auth form with many fields in it where one of fields is image. I have created multer middleware to store the image in my local server and I would pass the localpath of the image in cloudinary to upload image on their server. But request.file is coming undefined. After some debugging I got to know that the storage method of multer is not getting invoked even after calling it.
Can anyone point out the mistake I am doing? I am sharing the code for reference.
/app/api/profile/route.js
import { connect } from '@dbConfig/dbConfig';
import User from '@models/UserModel';
import { NextResponse } from 'next/server';
import { upload } from '@middleware/multer.middleware.js';
import { uploadOnCloudinary } from '@helpers/cloudinary.js';f
connect();
export const config = {
api: {
bodyParser: false
}
};
export async function POST(request) {
try {
// Wrapping Multer inside a Promise for async/await support
const multerUpload = () =>
new Promise((resolve, reject) => {
upload.single('profilePhoto')(request, null, function (err) {
if (err) {
console.log("Error during Multer upload:", err.message);
return reject(err); // Reject if error occurs
}
if (!request.file) {
console.log("No file uploaded");
return reject(new Error("No file uploaded"));
}
resolve(request.file); // Resolve with the file object if success
});
});
const file = await multerUpload(); // Invoke the middleware and wait for completion
// Now that the file is available, continue with the other logic
console.log("File uploaded successfully:", file);
const reqBody = await request.json();
const { username, highlights, designation, institute, bio, id } = reqBody;
const user = await User.findOneAndUpdate(
{ _id: id },
{ username, highlights, designation, institute, bio },
{ new: true }
);
if (!user) {
return NextResponse.json({ error: "User doesn't exist" }, { status: 404 });
}
const profilephotolocalpath = file.path;
const avatar = await uploadOnCloudinary(profilephotolocalpath);
if (avatar?.url) {
user.profilePhoto = avatar.url;
await user.save();
}
return NextResponse.json({
message: "Profile details updated successfully",
success: true,
user
});
} catch (error) {
console.log("Error in the API route:", error.message);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
/middleware/multer.middleware.js
import multer from "multer";
console.log("welcome to multer")
const storage = multer.diskStorage({
destination: function (req, file, cb) {
console.log("inside callback");
cb(null, "../public/assets/upload")
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.originalname + '-' + uniqueSuffix)
}
})
console.log("bye from multer")
export const upload = multer({ storage:storage })