Skip to content

Instantly share code, notes, and snippets.

@tonyspiro tonyspiro/index.js
Last active Aug 23, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.