- Install the necessary packages using the following command:
npm install cloudinary multer
- Create a
multer
middleware to handle file uploads:
const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
- Set up the Cloudinary configuration:
const cloudinary = require('cloudinary').v2;
cloudinary.config({
cloud_name: 'your_cloud_name',
api_key: 'your_api_key',
api_secret: 'your_api_secret'
});
- Create an API route to handle the file upload:
import nextConnect from 'next-connect';
import middleware from '../../../middleware/database';
import { ObjectID } from 'mongodb';
import formidable from 'formidable-serverless';
import cloudinary from 'cloudinary';
const handler = nextConnect();
handler.use(middleware);
handler.post(async (req, res) => {
const form = new formidable.IncomingForm();
form.parse(req, async (err, fields, files) => {
if (err) {
console.error('Error uploading image', err);
res.status(500).json({ error: 'Error uploading image' });
return;
}
const image = files.file.path;
const result = await cloudinary.v2.uploader.upload(image);
res.json({ url: result.secure_url });
});
});
export default handler;
- Create a form in your React component to handle the file upload:
import React, { useState } from 'react';
import axios from 'axios';
export default function ImageUpload() {
const [image, setImage] = useState(null);
const handleFileChange = (e) => {
setImage(e.target.files[0]);
};
const handleUpload = async () => {
const formData = new FormData();
formData.append('file', image);
try {
const res = await axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
console.log('Image uploaded:', res.data.url);
} catch (error) {
console.error('Error uploading image', error);
}
};
return (
<div>
<input type="file" onChange={handleFileChange} />
<button onClick={handleUpload}>Upload</button>
</div>
);
}