I'm working on creating an upload/download images feature in Node.js. So far there is the POST request which saves the image as binary in MongoDB and also a GET request which returns that image back. But I don't know how can I use that response, it is an array of numbers and don't know how to transform it.
Here is the Mongo Model:
image.js const mongoose = require('mongoose'); const Schema = mongoose.Schema;
const ImageItem = new Schema({
id: {
type: String
},
value: {
type: Buffer
},
});
module.exports = Image = mongoose.model('image', ImageItem);
the POST image which creates an entry in DB:
const image = require('../models/image');
const user = require('../models/user');
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
cb(null, file.originalname + new Date().toISOString());
},
});
const upload = multer({
storage: storage,
});
module.exports = function (app) {
app.post('/upload', upload.single('value'), (req, res, next) => {
const newImage = new image({
id: req.body.id,
value: req.file.path,
});
newImage
.save()
.then((result) => {
console.log(result);
res.status(201).json({
message: 'created succesfully',
});
})
.catch((err) => {
console.log(err);
res.status(500).json({
error: err,
});
});
});
};
and the entry created in DB:
for getting the image I created a GET request:
const image = require('../models/image');
module.exports = function (app) {
app.get('/upload/:id', (req, res) => {
console.log('req.body.id', req.params);
image.find({ id: req.params.id }, function (err, results) {
if (err) {
res.send(`error: ${err}`);
} else {
res.send(results);
}
});
});
};
which tested in Postman returns a JSON containing an array of numbers:
[
{
"_id": "5ebd1c112892f4230d2d4ab4",
"id": "[email protected]",
"value": {
"type": "Buffer",
"data": [
117,
112,
108,
111,
97,
100,
115,
47,
117,
115,
101,
114,
80,
105,
99,
116,
117,
114,
101,
46,
112,
110,
103,
50,
48,
50,
48,
45,
48,
53,
45,
49,
52,
84,
49,
48,
58,
50,
51,
58,
49,
51,
46,
57,
51,
52,
90
]
},
"__v": 0
}
]
How can I use this data to get the actual image?
