How to serve a file not saved in folder, stored in postgresql database, and to be rendered to HTML by expressjs?
We first sent the file to be posted as following:
router.post('/savefile', multer().single('filesource'), (q,s) => {
db.query("insert into filesource (filerefid, source) values ($1, $2) returning filerefid", [ q.body.filerefid, q.file ])
.then (r=> s.send(r.rows[0]))
})
And then tried to show that as following to the HTML:
<object type="application/pdf" data="http://localhost:3000/getsource/1"></object>
Which is requested by:
router.get('/getsource/:i', (q,s) => {
db.query('select source from filesource where filerefid = $1;',
[q.params.i])
.then (r=> s.send(Buffer.from(r.rows[0].source.buffer)))
})
However the files cant be showed or downloaded correctly like that, What is the best way of doing that, without saving file in any directory?
I suppose you are missing content type header in the response.
res.set('Content-Type', 'application/pdf');
Also consider setting Content-Disposition
header to present a correct file name.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
Content-Type: application/pdf
Content-Disposition: attachment; filename="file.pdf"
Update
file
property which is provided by multer is a js object, which contains buffer
property with binary data of the file. In http get method this binary data should be returned decorated by the required http headers mentioned above.