Currently I'm able to store pdf files in MongoDB using GridFSBucket. Now here's where the fun starts. I need a way to retrieve the file from mongo, and send it over from my app.js(backend) to my frontend files where the request responses are handled. I assume I have to pipe the file from a stream into my response and send it back. Can someone please explain or show some code of 1.sending the actual response with the pdf file on the server-side 2.handling the response on the client-side so the file can be displayed. Note: when displaying the file in the browser, I use pdf.js which takes the Pdf as a typed array(Uint8Array) so that's the ideal end form for the response data.
Basically I'm looking for the code that will fill the "TO DO" sections of the code below. Thanks
Here's some code:
Frontend:
var savePDF = function(blob){
//fs.writeFile("test.pdf",blob);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200){
//TO DO: Handle the file in the response which we will be displayed.
}
};
xhr.open("POST","/pdf",true);
xhr.send(blob);
};
Backend:
app.post('/pdf',function(req,res){
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
if(err) return console.dir(err);
console.log("Connected to Database");
var bucket = new GridFSBucket(db, { bucketName: 'pdfs' });
var CHUNKS_COLL = 'pdfs.chunks';
var FILES_COLL = 'pdfs.files';
// insert file as test.pdf
var uploadStream = bucket.openUploadStream('test.pdf');
var id = uploadStream.id;
uploadStream.once('finish', function() {
console.log("upload finished!")
// TO DO: Now that the file is stored in the DB, retrieve it and send it
// with the response.
});
// This pipes the POST data to the file
req.pipe(uploadStream);
});
});
via ribarcheto94
No comments:
Post a Comment