Using multer file upload in next js in the app router
Unanswered
Sphynx posted this in #help-forum
SphynxOP
Im trying to use multer to appload a picture but its not working and there are no errors
import Post from "@models/Post";
import User from "@models/User";
import { connectToDB } from "@utils/database";
import { NextResponse } from "next/server";
import upload from "../upload/route";
export const POST = async req => {
try {
// Call the multer upload middleware here
upload(req, res, async err => {
if (err) {
return NextResponse.json({ message: err.message }, { status: 500 });
}
await connectToDB();
const { userId, text, picturePath } = req.body;
const user = await User.findById(userId);
if (!user) {
return NextResponse.json(
{ message: "User not found" },
{ status: 404 }
);
}
// If the file is uploaded successfully, multer will have added the file path to req.file
console.log(picturePath);
const newPost = new Post({
userId,
firstName: user.firstName,
lastName: user.lastName,
text,
picturePath,
userPicturePath: user.picturePath,
});
await newPost.save();
return NextResponse.json({ message: "Post created" }, { status: 201 });
});
// return NextResponse.json({ message: "Post created" }, { status: 201 });
} catch (error) {
return NextResponse.json({ message: error.message }, { status: 500 });
}
};
import Post from "@models/Post";
import User from "@models/User";
import { connectToDB } from "@utils/database";
import { NextResponse } from "next/server";
import upload from "../upload/route";
export const POST = async req => {
try {
// Call the multer upload middleware here
upload(req, res, async err => {
if (err) {
return NextResponse.json({ message: err.message }, { status: 500 });
}
await connectToDB();
const { userId, text, picturePath } = req.body;
const user = await User.findById(userId);
if (!user) {
return NextResponse.json(
{ message: "User not found" },
{ status: 404 }
);
}
// If the file is uploaded successfully, multer will have added the file path to req.file
console.log(picturePath);
const newPost = new Post({
userId,
firstName: user.firstName,
lastName: user.lastName,
text,
picturePath,
userPicturePath: user.picturePath,
});
await newPost.save();
return NextResponse.json({ message: "Post created" }, { status: 201 });
});
// return NextResponse.json({ message: "Post created" }, { status: 201 });
} catch (error) {
return NextResponse.json({ message: error.message }, { status: 500 });
}
};
1 Reply
Polar bear
I am in the same situation