I have a messaging app and when a user sends an image as a message there are two separate items being sent to the database, one being the message object which stores the image name, user name, etc. Then the other being the image itself using gridFS.
// here i wait for the client to make a POST to this route
// multiparty handles the file and then gridFS handles adding the image from
// that form to the mongodb database
app.post('/upload', function(req,res){
form.on('part', function(part){
if(!part.filename) return;
size = part.byteCount;
fileName = part.filename;
});
form.on('file', function(name,file){
var tempfile = file.path;
var origname = fileName;
var writestream = gfs.createWriteStream({ filename: origname });
fs.createReadStream(tempfile).on('end', function () {
res.send('<p><h1>Upload Complete!</h1><p>');
}).on('error', function () {
res.send('Error, upload failed!');
}).pipe(writestream);
});
form.parse(req);
});
The essence of this code above is that it adds the image from the html form onto my server. Then in order to get that image I can make that request using it's id as you can see below.
app.get('/image/:id', function(req,res){
console.log(req.params.id)
gfs.createReadStream({_id:req.params.id}).pipe(res);
});
This works wonders in an img
tag because I can use this <img src="http://localhost:3300/image/5403ec41543c4bc00cf88c8e">
to show the image.
I am not sure how I can associate the message to retrieve the proper route id, the best I can think of is having them both use the same id's but I am not sure how I can make them the same?
Thanks.