Table of Contents
Next.js is a powerful React framework that makes it easy to build web applications. In this article, we’ll cover how to implement file uploads in a Next.js application using a simple form and API route. We’ll use the multer library to handle file uploads on the server side.
Steps for Uploading Files in Next.js
Step 1: Setting Up a New Next.js Project
Initialize a New Project
npx create-next-app@latest nextjs-file-upload cd nextjs-file-upload
Start the Development Server
npm run dev
Step 2: Installing Necessary Packages
We need multer to handle file uploads on the server.
Install Multer
npm install multer
Step 3: Creating the Upload Form
First, let’s create a simple form to upload files.
Create the Upload Form Page
// pages/upload.js import { useState } from 'react'; export default function Upload() { 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); await fetch('/api/upload', { method: 'POST', body: formData, }); alert('File uploaded successfully!'); }; return ( <div> <h1>Upload File</h1> <form onSubmit={handleSubmit}> <input type="file" onChange={handleFileChange} /> <button type="submit">Upload</button> </form> </div> ); }
Step 4: Creating the API Route for File Upload
Next, let’s create an API route to handle the file upload.
Create the Upload API Route
// pages/api/upload.js import nextConnect from 'next-connect'; import multer from 'multer'; const upload = multer({ storage: multer.diskStorage({ destination: './public/uploads', filename: (req, file, cb) => cb(null, file.originalname), }), }); const apiRoute = nextConnect({ onError(error, req, res) { res.status(501).json({ error: `Something went wrong: ${error.message}` }); }, onNoMatch(req, res) { res.status(405).json({ error: `Method ${req.method} Not Allowed` }); }, }); apiRoute.use(upload.single('file')); apiRoute.post((req, res) => { res.status(200).json({ data: 'File uploaded successfully' }); }); export default apiRoute; export const config = { api: { bodyParser: false, }, };
Step 5: Creating the Upload Directory
Create a directory named uploads inside the public directory. This is where uploaded files will be stored.
mkdir -p public/uploads
Step 6: Running the Application
Start the Next.js development server.
npm run dev
Open your browser and navigate to http://localhost:3000/upload to see the file upload form in action.
Conclusion
In this article, we covered how to implement file uploads in a Next.js application. We created an upload form, set up an API route to handle file uploads using multer, and stored the uploaded files on the server. This basic implementation can be expanded and customized based on your specific requirements.
For more updates on programming trends and tutorials, visit blogsea.net regularly.
Uploading Files in Next.js – FAQs
Multer handles file uploads on the server side by processing multipart/form-data.
Set bodyParser: false in the config export of the API route.
Yes, set a file size limit using the limits option in multer.
The uploaded file is available in req.file after multer processes the upload.
nextConnect is used to handle middleware and route handlers more efficiently in Next.js API routes.