Last active
November 28, 2024 19:36
-
-
Save 1travelintexan/0f0a66b641a4536bfd0e7216e8557619 to your computer and use it in GitHub Desktop.
Cloudinary with only a frontend
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Video going step by step to create cloudinary account and upload image | |
//https://www.youtube.com/watch?app=desktop&v=Y-VgaRwWS3o | |
//before anything on the React code, create a free account with Cloudinary and follow the video above to create a upload preset | |
//you will need the cloudinary dashboard for data to put inside your POST request | |
//create a state for the image | |
const [image, setImage] = useState('') | |
//create a function to call when you submit the form | |
function handleImage(e) { | |
//stop form from reloading the page | |
e.preventDefault(); | |
//create a form data to send to cloudinary | |
const formData = new FormData(); | |
//use the .append method to add properties to the form data | |
formData.append("file", image); | |
//upload_preset is a specific name and you get the value from your cloudinary dashboard | |
//this comes from the cloudinary dashboard | |
formData.append("upload_preset", "IronhackWD"); | |
//make an axios post request to this endpoint but change 'dxurcuyga' to your cloud name! | |
//the second argument should be the formData that you created and appended the information to. | |
axios | |
.post("https://api.cloudinary.com/v1_1/dxurcuyga/image/upload", formData) | |
//if successful then you should get a response and in that response you will receive a 'res.data.url' key that is your image hosted with an https | |
//if you are in the .then block then now you have an https that you can include in your next axios request that sends data to your json server | |
.then((res) => console.log(res)) | |
.catch((err) => console.log(err)); | |
} | |
//put a form in the return of your component with an input of type 'file' | |
<form onSubmit={handleImage}> | |
//onChange of the input, set the state of image to the event.target.files[0] | |
//witht the type='file' you will receive an array of files so you need to select the first at index 0 | |
<input type="file" onChange={(e)=>setImage(e.target.files[0])} /> | |
<button>submit</button> | |
</form> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment