Learn how to upload images to Cloudinary using JavaScript's Fetch API. This tutorial walks through setting up upload parameters with FormData and making HTTP requests to upload images programmatically from the browser.
This video is brought to you by Cloudinary's video player - embed your own!
Use the controls to set the playback speed, navigate to chapters of interest and select subtitles in your preferred language.
You can find the code from this tutorial in
GitHub.
This tutorial presents the following topics. Click a timestamp to jump to that part of the video.
|
|
0:00 |
The Fetch API is the standard way to make HTTP requests from the browser. You can use it to get data from an API, submit forms to a backend, or upload media like images and videos to a server. |
|
|
0:25 |
This simple application is built using vanilla JavaScript. It has an input to choose images to upload, a button to start the upload, and displays the file paths of selected images and the uploaded images after they've been processed. |
|
|
1:01 |
The HTML includes a form element that wraps an input for choosing images and a button to submit the form. Everything is tied together with a main.ts file that sets up listeners and handlers on the input and form elements. |
|
|
1:30 |
Use the browser's built-in Fetch API to communicate with Cloudinary's Upload API. Start by defining the fetch call with the upload endpoint URL (https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/image/upload) and specify the HTTP method as POST. |
|
|
2:12 |
Cloudinary's REST API uses FormData to pass information from the client to the server. Initialize a new FormData object and use the append method to add the file you want to upload. Include the FormData in the fetch request body. |
|
|
2:50 |
In the Cloudinary Console, navigate to Settings > Upload > Upload presets to create upload presets so you don't have to specify upload parameters every time. You can create unsigned or signed versions depending on your security requirements. |
|
|
3:25 |
Append the upload preset to your FormData using formData.append('upload_preset', 'your_preset_name'). This tells Cloudinary which preset configuration to use for the upload. |
|
|
3:36 |
After sending the fetch request, parse the response using await response.json(). The response includes an object representing the uploaded image with the URL from Cloudinary where the image now lives, along with other metadata like the public ID. |
|
|
4:17 |
Choose an image to upload, press the upload button, and see the preview show up properly. Check your Cloudinary Media Library to confirm the image was successfully uploaded using just vanilla JavaScript and the Fetch API. |
Check out the Cloudinary Academy for free self-paced Cloudinary courses on a variety of developer or DAM topics, or register for formal instructor-led courses, either virtual or on-site.