admin管理员组文章数量:1201413
I am working on an API in Next.js 14+ where I need to upload files. Here are the fields I am using:
name: string description: string profile_picture: single image documents: multiple files images: multiple files I want to save the uploaded files in the public/uploads directory within my project.
I am trying to use multer to handle file uploads, but I am encountering an issue: I cannot receive files or the request body in my API.
I am using MongoDB to save the file paths. Despite following the proper steps, I am unable to receive files or the body content in the request. How can I fix this issue? Does the bodyparser false
configuration in the API work properly with file uploads in Next.js 14+?
Here's my code:
import mongoose from 'mongoose';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
const uploadDirectory = path.join(process.cwd(), 'public/uploads');
if (!fs.existsSync(uploadDirectory)) {
fs.mkdirSync(uploadDirectory, { recursive: true });
}
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadDirectory);
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
},
});
const upload = multer({ storage });
const uploadMiddleware = upload.fields([
{ name: 'profile_image', maxCount: 1 },
{ name: 'other', maxCount: 10 },
{ name: 'images', maxCount: 10 },
]);
export const POST = async (req) => {
try {
console.log("Hitting The API.");
await new Promise((resolve, reject) => {
uploadMiddleware(req, res, (err) => {
if (err) return reject(err);
resolve();
});
});
const { name, desc } = req.body;
const profileImage = req.files['profile_image']?.[0]?.path.replace(/\\/g, '/') || null;
const otherFiles = req.files['other']?.map((file) => file.path.replace(/\\/g, '/')) || [];
const imageFiles = req.files['images']?.map((file) => file.path.replace(/\\/g, '/')) || [];
const record = await Record.create({
name,
desc,
profile_image: profileImage,
other: otherFiles,
images: imageFiles,
});
return new Response(
JSON.stringify({ success: true, record }),
{ status: 201, headers: { 'Content-Type': 'application/json' } }
);
} catch (error) {
return new Response(
JSON.stringify({ success: false, error: error.message }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
};
export const config = {
api: {
bodyParser: false,
},
};
本文标签:
版权声明:本文标题:nextjs api router - How to create API with multiple text and file Fields in Next JS 14 with multer? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738574704a2100805.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论