Skip to content

Instantly share code, notes, and snippets.

@ManishPoduval
Last active October 20, 2020 15:52
Show Gist options
  • Save ManishPoduval/672ef8aebd060702f1aea8f79463e37f to your computer and use it in GitHub Desktop.
Save ManishPoduval/672ef8aebd060702f1aea8f79463e37f to your computer and use it in GitHub Desktop.
Cloudinary Setup
// You need to run `npm i cloudinary multer-storage-cloudinary multer` to use cloudinary
// create this file in the 'config' folder
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');
const multer = require('multer');
// once you register on cloudinary you will get these three keys.
// store them in the .env file and reference them here
cloudinary.config({
cloud_name: '',
api_key: '',
api_secret: ''
});
const storage = new CloudinaryStorage({
cloudinary,
folder: 'todo-gallery', // The name of the folder in cloudinary . You can name this whatever you want
allowedFormats: ['jpg', 'png'],
// params: { resource_type: 'raw' }, => this is in case you want to upload other type of files, not just images
filename: function (req, res, cb) {
cb(null, res.originalname); // The file on cloudinary would have the same name as the original file name
}
});
module.exports = multer({ storage });
const express = require('express');
const router = express.Router();
// include CLOUDINARY:
const uploader = require('../config/cloudinary.config.js');
// ensure you have an input type like this in your hbs file
/*
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="imageUrl" accept="image/png, image/jpg">
<button type="submit">Submit</button>
</form>
*/
// imageUrl is the input name in your hbs file
router.post('/upload', uploader.single("imageUrl"), (req, res, next) => {
console.log('file is: ', req.file)
if (!req.file) {
next(new Error('No file uploaded!'));
return;
}
//You will get the image url in 'req.file.path'
//store that in the DB
})
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment