upload image to server next js
- Install the required dependencies:
npm install formidable
- 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' });
});
});
}
Create the
public/uploads
directory to store uploaded images.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;
- 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;
- Start your Next.js application:
npm run dev
Visit http://localhost:3000
in your browser and test the image upload functionality.