• learn nextjs
  • Posts
  • Next.js File Upload Solutions: Methods Using FormData & Fetch API, and Multer & Express

Next.js File Upload Solutions: Methods Using FormData & Fetch API, and Multer & Express

Question:

Next.js File Uploads: Server-Side Solutions,I get a lot of questions about forms on NextJS, and a lot of them have to do with posting files to the server. If you've worked in other frameworks you are probably expecting that uploading files is a huge pain, but in NextJS it's actually quite simple. In this article, I'll show you how to upload files to the server using NextJS two different methods.

Answer:

Sure, I can guide you through two different methods of uploading files to the server using Next.js.

Method 1: Using FormData and fetch API

  1. Create a form in your Next.js component:

import React, { useState } from 'react';

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

  const handleSubmit = (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('file', file);

    fetch('/api/upload', {
      method: 'POST',
      body: formData,
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch((error) => {
      console.error('Error:', error);
    });
  };

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

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

export default UploadForm;
  1. Create an API route in Next.js to handle the file upload:

// pages/api/upload.js
import formidable from 'formidable';
import fs from 'fs';

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

const handler = async (req, res) => {
  if (req.method === 'POST') {
    const form = new formidable.IncomingForm();
    form.uploadDir = './public';
    form.keepExtensions = true;

    form.parse(req, (err, fields, files) => {
      if (err) {
        res.status(500).json({ error: err });
      } else {
        res.status(200).json({ files });
      }
    });
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
};

export default handler;

Method 2: Using Multer and Express

  1. Install the necessary packages:

npm install express multer
  1. Create a server.js file in the root of your project:

const express = require('express');
const multer = require('multer');
const path = require('path');

const upload = multer({ dest: 'uploads/' });
const app = express();

app.post('/upload', upload.single('file'), (req, res) => {
  res.json({ success: true });
});

app.listen(3000, () => console.log('Server started on port 3000'));
  1. Modify your form to point to the new server:

const handleSubmit = (e) => {
  e.preventDefault();
  const formData = new FormData();
  formData.append('file', file);

  fetch('http://localhost:3000/upload', {
    method: 'POST',
    body: formData,
  })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch((error) => {
    console.error('Error:', error);
  });
};

Remember to run your server with node server.js.

These are two different methods to upload files in Next.js. The first one uses the built-in fetch API and a custom API route, while the second one uses Express and Multer. Choose the one that best fits your needs

Reply

or to participate.