This is a Next.js project built with the image upload to the Cloudinary
.
First, run the development server:
npm run dev
# or
yarn dev
Open http://localhost:3000 with your browser to see the result.
You can start editing the page by modifying pages/index.js
. The page auto-updates as you edit the file.
The Image Upload
Component is created inside the Components folder in the root directory.
To connect to the cloud you should create a preset in the settings. Follow the following steps
- Go to the Settings Tab
- Move to Upload Tab
- Navigate to the Upload Presets and click on
Add upload preset
.
- In the Upload Preset Name give a name to the preset. Remember this name will be used to use this preset to upload the images to the Cloudinary.
import axios from "axios";
import { useState } from "react";
const Upload = () => {
const [selectedImage, setSelectedImage] = useState("");
const [cloudUrl, setCloudUrl] = useState("");
// Here the preset_name is the name you used to create the preset
// and the cloud_name is the name of your cloud.
const handleUpload = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("file", selectedImage);
formData.append("upload_preset", preset_name);
axios
.post(`https://api.cloudinary.com/v1_1/${cloud_name}/image/upload`, formData)
.then((res) => {
setCloudUrl(res.data.url);
})
.catch((err) => console.error(err));
};
return (
<div>
<div>
<h1>Upload Component</h1>
</div>
<div>
<input type="file" onChange={(e) => setSelectedImage(e.target.files[0])} />
{cloudUrl && (
<div className="w-96 h-96">
<img
src={cloudUrl}
alt="bgImage"
className="object-cover w-full h-full rounded-full"
/>
</div>
)}
</div>
<button onClick={handleUpload}>Upload</button>
</div>
);
};
export default Upload;