How to Upload Media to Your Bucket Using the Cosmic JS API
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
Getting Started
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.
<html>
<body>
<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!" />
</form>
</body>
</html>
Next let’s add a file and let it rip. Notice we now have data to use for data fetching / storing:
{
"media": {
"name": "57319310-b914-11e6-acef-b1b7e94fa195-earth.png",
"original_name": "earth.png",
"size": 1024912,
"type": "image/png",
"bucket": "5839c67f0d3201c114000004",
"created": "2016-12-03T04:52:49.516Z",
"location": "https://cosmicjs.com/uploads",
"url": "https://cosmicjs.com/uploads/57319310-b914-11e6-acef-b1b7e94fa195-earth.png",
"imgix_url": "https://cosmicjs.imgix.net/57319310-b914-11e6-acef-b1b7e94fa195-earth.png",
}
}
The Power of Imgix
?w=640
” 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:
POST /v1/:your-bucket-slug/add-object
{
"title": "New Object",
"slug": "new-object",
"type_slug": "tests",
"content": "",
"metafields": [{
"type": "file",
"title": "Image",
"key": "image",
"value": "57319310-b914-11e6-acef-b1b7e94fa195-earth.png"
}]
}
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.