In your React app, you may need to upload Images or Videos from your machine, either to send them to a backend API or to just display the uploaded image.
For we will be using Cloudinary, which streamlines media management and improves user experience by automatically delivering images and videos, enhanced and optimized for every user.
We will be uploading the images to Cloudinary and getting them back, it will work as sort of pushing data to an API and fetching the scent data.
Letβs get started.
Go to [https://cloudinary.com](https://cloudinary.com/) and sign up.
Enter your role
Select the project you want to do.
Head over to your dashboard where you will see your cloud Name
We also need to have an upload preset. Go to settings using a small icon on the bottom left of the sidebar.
Under product environment settings, click on upload, scroll down until you see upload presets.
Click on add upload preset.
You will see a form like this.
The signing mode by default will be signed, CHANGE it to signed and save.
10 . To upload an image or a video, you will need 2 things
Cloud Name
Upload Preset Name
REACT CODE
In react, we shall be handling an on-change function on an input with the type of file.
The code for a file input is as follows
This on the browser looks like this
We will make a function for the onChange event listener for this input file that will post the media file we pick from our local machine, send it to Cloudinary, and send a GET request to our cloud name to get the uploaded media file. This will come back in the form of a string URL which we can store in the state.
We shall have a component called Input.js, here we shall have an empty state for images and videos.
This is the structure of the code for Images.
import React, { useState } from "react";
function Input() {
const [image, setImage] = useState("");
const uploadImage = (files) => {
const formData = new FormData();
formData.append("file", files[0]);
formData.append("upload_preset", "<your upload preset>");
fetch(
"https://api.cloudinary.com/v1_1/<your cloud name>/image/upload",
{
method: "POST",
body: formData,
}
)
.then((response) => response.json())
.then((data) => {
setImage(data.secure_url);
});
};
return <div>
<input type="file" onChange={(e) => uploadImage(e.target.files)} />
<img
src={image}
alt="uploaded image"
/>
</div>;
}
export default Input;
in the uploadImage function, on formData.append, add your upload preset name and on the API endpoint you are fetching from add your cloudname .
You will get the image string back and set it in the Image state. You can then display the image by using the img tag and the src as the image state, or you can send this image URL to a backend API.
This is the structure of the code for Videos
import React, { useState } from "react";
function Input() {
const [video, setVideo] = useState("");
const uploadVideos = (files) => {
const formData = new FormData();
formData.append("file", files[0]);
formData.append("upload_preset", "<your upload preset>");
fetch("https://api.cloudinary.com/v1_1/<your cloud name>/video/upload", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((data) => {
setImage(data.secure_
url);
});
};
return (
<div>
<input type="file" onChange={(e) => uploadVideos(e.target.files)} />
<video src={video} controls />
</div>
);
}
export default Input;
in the uploadVideo function , on formData.append, add your upload preset name and on the API endpoint you are fetching from add your cloudname.
You will get the video string back and set it in the Image state. You can then display the image by using the IMG tag and the src as the image state or you can send this image URL to a backend API.
This is the structure of the code for Audios
import React, { useState } from 'react';
const AudioUpload = () => {
const [audioUrl, setAudioUrl] = useState(null);
const handleAudioUpload = async (event) => {
const file = event.target.files[0];
if (!file) return; // Handle no file selected case
const formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', 'YOUR_UPLOAD_PRESET'); // Replace with your Cloudinary upload preset
try {
const response = await fetch(
`https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/video/upload`, // Specify resource type as 'audio'
{
method: 'POST',
body: formData,
}
);
const data = await response.json();
setAudioUrl(data.secure_url);
} catch (error) {
console.error('Error uploading audio:', error);
// Handle upload errors gracefully (e.g., display error message to user)
}
};
return (
<div>
<input type="file" accept="audio/*" onChange={handleAudioUpload} />
{audioUrl && (
<audio controls>
<source src={audioUrl} type="audio/mpeg" />
</audio>
)}
</div>
);
};
export default AudioUpload;
Note: Cloudinary treats audio uploads as video assets.
Top comments (3)
straight to point
Crystal clear. Thank you so much...
Awesome guide, mate! Thanks so much!