skip to Main Content

I’m developing a project using Next.js, and I need to manage file uploads. I’m attempting to use the formidable library to handle these uploads on the server side, but I’m encountering some problems.

When I attempt to upload a file, I get a 500 error without any specific message.

What could be causing this error?
Do I need any extra settings or steps to correctly manage file uploads with formidable in a Next.js API route?
Here’s my current setup:

import formidable from 'formidable';
import fs from 'fs';

export const config = {
    api: {
        bodyParser: false,
    },
};

export default async (req, res) => {
    const form = new formidable.IncomingForm();

    form.parse(req, (err, fields, files) => {
        if (err) {
            res.status(500).send(err);
            return;
        }

        const oldPath = files.file.filepath;
        const newPath = `./public/uploads/${files.file.originalFilename}`;

        fs.rename(oldPath, newPath, (err) => {
            if (err) {
                res.status(500).send(err);
                return;
            }

            res.status(200).send('File uploaded successfully');
        });
    });
};


My JSX


import { useState } from 'react';

const Home = () => {
    const [file, setFile] = useState(null);

    const handleFileChange = (e) => {
        setFile(e.target.files[0]);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        const formData = new FormData();
        formData.append('file', file);

        const res = await fetch('/api/upload', {
            method: 'POST',
            body: formData,
        });

        if (res.ok) {
            console.log('File uploaded successfully');
        } else {
            console.error('File upload failed');
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <input type="file" onChange={handleFileChange} />
            <button type="submit">Upload</button>
        </form>
    );
};

export default Home;


2

Answers


  1. Try copying code from this repo: https://github.com/tuffstuff9/nextjs-pdf-parser. Doesn’t use formidable iirc but will do the trick.

    Login or Signup to reply.
  2. I faced a similar challenge a few months back so nothing really worked with the default config of next js. So I created a custom server and used multer since I was familiar with multer.

    A rough server.js would like this:

    const multer = require('multer');
    const multerUpload = multer({ storage: multer.memoryStorage() });
    server.post('/api/upload', multerUpload.fields([{ name: 'image', maxCount: 1 }]), async (req, res) => { 
    const file = req.files.image[0];
    // Do something with the file
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search