upload image to server next js

  1. Install the required dependencies:
npm install formidable
  1. Create an API route for handling the image upload. In the pages/api directory, create a file (e.g., upload.js).
// pages/api/upload.js
import formidable from 'formidable';
import fs from 'fs';

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

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

  form.parse(req, (err, fields, files) => {
    const oldPath = files.file.path;
    const newPath = `public/uploads/${files.file.name}`;

    fs.rename(oldPath, newPath, (err) => {
      if (err) throw err;
      res.status(200).json({ message: 'File uploaded successfully' });
    });
  });
}
  1. Create the public/uploads directory to store uploaded images.

  2. Create a component to handle file input and submission in your React component.

// components/FileUpload.js
import { useState } from 'react';

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

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

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

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

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

      if (response.ok) {
        console.log('File uploaded successfully');
      } else {
        console.error('Error uploading file');
      }
    } catch (error) {
      console.error('Error uploading file', error);
    }
  };

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

export default FileUpload;
  1. Use the FileUpload component in your page.
// pages/index.js
import FileUpload from '../components/FileUpload';

const Home = () => {
  return (
    <div>
      <h1>Image Upload</h1>
      <FileUpload />
    </div>
  );
};

export default Home;
  1. Start your Next.js application:
npm run dev

Visit http://localhost:3000 in your browser and test the image upload functionality.