Skip to content

Instantly share code, notes, and snippets.

@sunapi386
Last active July 14, 2018 01:25
Show Gist options
  • Select an option

  • Save sunapi386/2bee663174a0b8136c7396e5d04ca895 to your computer and use it in GitHub Desktop.

Select an option

Save sunapi386/2bee663174a0b8136c7396e5d04ca895 to your computer and use it in GitHub Desktop.
Convert a base64 string from mongodb as image
# POST the images onto the server
curl --header "Content-Type: application/json" \
--request POST \
--data \
'{"name":"test-image-10","data":"'(base64 -w 0 test-image-10.jpg)'"}' \
"http://localhost:8081/images"
# Retrieve it
wget "localhost:8081/images/5b492c74de7212532da231cc" -O filename.jpg
const base64Img = require('base64-img');
function getImage() {
return (req, res) => {
const needle = req.params[id];
model.findById(needle)
.then(result => {
// return res.send(result);
const name = result._doc.name;
const base64str = result._doc.data.toString();
const prefix =
'data:image/jpg;base64,'; // wtf IDK why this is needed by 'base64-img' but ok
base64Img.img(prefix + base64str, '/tmp/lbs-imgs/', name, (err, filepath) => {
if (err) {
return res.status(500).send(
{message: `Image ${req.params[id]} failed to decode: ${e}`});
} else {
return res.sendFile(filepath);
}
});
})
.catch(error => {
if (error.kind === 'ObjectId') {
return res.status(404).send({message: `Image ${req.params[id]} not found`});
}
res.status(500).send({message: error.message});
})
}
}
// https://github.com/chriso/validator.js
const nameValidator = [
mongooseValidate({
validator: 'isLength',
arguments: [3, 150],
message: 'Name should be between {ARGS[0]} and {ARGS[1]} characters',
}),
mongooseValidate({
validator: 'isAscii',
passIfEmpty: false,
message: 'Name should contain alpha-numeric characters only',
}),
];
const imgValidator = [
// base64
mongooseValidate({
validator: 'isLength',
passIfEmpty: true,
arguments: [0, 16000000],
message: 'Image size must be between {ARGS[0]} and {ARGS[1]} bytes',
}),
mongooseValidate({
validator: 'isAscii',
passIfEmpty: false,
message: 'Name should contain alpha-numeric characters only',
}),
];
const ImageSchema = mongoose.Schema(
{
name: {type: String, required: true, unique: true, validate: nameValidator},
data: {type: Buffer, contentType: String, unique: true, validate: imgValidator}
},
{timestamps: true});
ImageSchema.plugin(mongoosePaginate);
module.exports = mongoose.model('Image', ImageSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment