Created
May 2, 2019 00:35
-
-
Save chamatt/f214294542416d5ccc51804871457bde to your computer and use it in GitHub Desktop.
Cloudinary Avatar Upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require("express"); | |
const router = express.Router(); | |
const passport = require("passport"); | |
// Multipart form data handler middleware | |
var multer = require("multer"); | |
var upload = multer({ dest: "uploads/" }); | |
const autoReap = require("multer-autoreap"); | |
// Cloudinary | |
var cloudinary = require("cloudinary"); | |
const CLOUDINARY_CONFIG = {} // Config object should go here | |
cloudinary.config(CLOUDINARY_CONFIG); | |
router.post( | |
"/avatar", | |
passport.authenticate("jwt", { session: false }), | |
upload.single("avatar"), | |
autoReap, | |
uploadAvatar | |
); | |
const uploadAvatar = (req, res) => { | |
User.findById(req.user.id) | |
.then(user => { | |
if (user.avatarId) { | |
cloudinary.v2.uploader.destroy(user.avatarId, function(err, result) { | |
if (err) | |
res | |
.status(400) | |
.json({ errors: { uploadfailed: "Failed uploading avatar" } }); | |
User.findOneAndUpdate( | |
{ _id: user._id }, | |
{ $set: { avatar: "", avatarId: "" } } | |
).catch(() => | |
res | |
.status(400) | |
.json({ errors: { uploadfailed: "Failed uploading avatar" } }) | |
); | |
}); | |
} | |
cloudinary.v2.uploader.upload( | |
req.file.path, | |
{ | |
folder: "work_log", | |
transformation: ["avatar_image"] | |
}, | |
(err, result) => { | |
if (err) { | |
console.log(err); | |
res | |
.status(400) | |
.json({ errors: { uploadfailed: "Failed uploading avatar" } }); | |
} | |
console.log(result); | |
User.findOneAndUpdate( | |
{ _id: user._id }, | |
{ $set: { avatar: result.url, avatarId: result.public_id } } | |
) | |
.then(() => { | |
res.json({ | |
success: true, | |
action: "upload", | |
data: { | |
avatar: result.url, | |
avatarId: result.public_id | |
} | |
}); | |
}) | |
.catch(() => | |
res.status(400).json({ | |
errors: { uploadfailed: "Failed uploading avatar" } | |
}) | |
); | |
} | |
); | |
}) | |
.catch(err => { | |
console.log(err); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment