0

I have schema that take two fields - name and file. file is Binary type and name is a String

I use this schema to save images as documents in my db

While the image is getting saved without issues - I am not sure how can I read it later. The main propose is to be able to search a file by its name using findOne and then to stream it to the response using pipe or any other solution that might work - to show the image to the client inside <img/> tag. I tried to convert the file to base64 and then to send something like res.send('data:image/png;base64,${file.file}') without much luck . * Note that because I have inside the document two fields (name and file) I need to stream only the file for obvious reasons

This is my GET request to fetch the file :

router.get('/:url',(req, res) => {
    const url = req.params.url;
    console.log(url)
    console.log('streaming file')
File.
    findOne({ name:url}, 'file').
    cursor().
    on('data', (doc) => { 
        console.log('doc', doc.file); 
        res.send(doc.file)
    }).
    on('end', () => { console.log('Done!'); });

})

this not helps because its for streaming file with path which I dont have. My file stored in a db

Image of the saved file inside the db: enter image description here

obiwankenoobi
  • 1,504
  • 5
  • 18
  • 37
  • Possible duplicate of [Stream files in node/express to client](https://stackoverflow.com/questions/13106096/stream-files-in-node-express-to-client) – mpm Aug 13 '18 at 11:46
  • @mpm not helping - you can read the edit to see why – obiwankenoobi Aug 13 '18 at 11:51
  • your file is stored in the db under what format? that's the real question here. is it binary or string? – mpm Aug 13 '18 at 12:11
  • @mpm "I have schema that take two fields - `name` and `file`. `file` is `Binary` type and `name` is a `String`" – obiwankenoobi Aug 13 '18 at 12:14
  • check the type of file property with console.log, it should be a Buffer which is compatible with node.js fs package thus you should be able to stream it with the method i linked https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options then pipe it to the response . it shouldn't be more complicated than the way you created doc.file at first place – mpm Aug 13 '18 at 12:24
  • @mpm its an object - I added an image to demonstrated the data strecture inside the db – obiwankenoobi Aug 13 '18 at 12:35

0 Answers0