0

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, 
    },
};

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.