Skip to content

Instantly share code, notes, and snippets.

@tonyspiro
Last active August 23, 2019 17:10
Show Gist options
  • Save tonyspiro/3c0e231857e99e88a6f668e314e69169 to your computer and use it in GitHub Desktop.
Save tonyspiro/3c0e231857e99e88a6f668e314e69169 to your computer and use it in GitHub Desktop.
Upload Media to Your Cosmic JS Bucket using Multer
// index.js
const fs = require('fs')
const Cosmic = require('cosmicjs')()
const multer = require('multer')
const express = require('express')
var app = express()
const bucket = Cosmic.bucket({
slug: 'your-bucket-slug',
write_key: ''
})
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + '/uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
app.post('/upload', upload.single('file'), async function(req, res) {
try {
const media_object = {
originalname: req.file.originalname,
buffer: fs.createReadStream(req.file.path)
}
const response = await bucket.addMedia({ media: media_object });
return res.json(response);
} catch (e) {
console.log(e)
}
});
app.listen(5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment