How to Upload Media to Your Bucket Using the Cosmic JS API
CEO & Co-Founder of Cosmic JS
Tony Spiro is the Co-Founder of Cosmic JS, an API-first Content Management Platform for building content-powered apps.
In this short tutorial I’m going to show you how to:
- Upload an image to your Cosmic JS Bucket via the Cosmic JS API.
- Alter your image using the powerful Imgix processing service (free with every Cosmic JS Bucket)
- Add the uploaded image as a Metafield to an Object in your Bucket
Sign up for Cosmic JS to create your own Bucket or just follow along with the examples.
To start, let’s create a simple HTML form to upload our media.
<form action="https://api.cosmicjs.com/v1/bucket-slug/media" method="post" enctype="multipart/form-data">
<input type="file" name="media" />
<input type="submit" value="Upload!" />
Next let’s add a file and let it rip. Notice we now have data to use for data fetching / storing:
The Power of Imgix
After we POST our media to our Cosmic JS Bucket, one of the pieces of data returned is an Imgix URL. Imgix gives us powerful image processing capability on the fly. By simply adding query parameters to the end of the Imgix url, we have the power to resize, crop, add filters and more to our uploaded images. For example, to resize this image to 2X mobile size just add “
” to the end of the URL:
Adding the Uploaded Image to an Object
After adding our image to our Cosmic JS Bucket we may want to add it to an Object. To do this we’ll simply take the “name” value returned after we POST our media and add it as a file Metafield value and POST this to our Add Object API endpoint:
"title": "New Object",
Now when we go into our Cosmic JS Bucket we’ll notice that the “Tests” Object Type has a new Object titled “New Object” with our newly uploaded file as a file Metafield.
Cosmic JS makes it really easy to add dynamic content to any website or application. In this tutorial I showed you how you can use the Cosmic JS API to add media, process images using the available Imgix processing URL then save that image to an Object in our Bucket for easy editing later. To learn more about how Cosmic JS makes it easy to store media and power content for your websites and apps, check out the Documentation page
Subscribe to get your daily round-up of top tech stories!