Meteor.js - Serve image directly from MongoDB?

Using Meteor.js, how can I serve an arbitrary HTTP response, for example. image or pdf?

Example 1 - I need to create PDF reports that I cannot store publicly or on a third-party server. Or a report can be generated in real time in response to an HTTP GET.

Example 2 - If I have a URL:

/images/myimage.png

I would like to detect this request on the server, read the image from MongoDB and execute it with the correct headers, so it is available for use with img tags, i.e.

<img src="/images/myimage.png">

I do not want to store the images in the / public / directory, so that I can have more control over what is served and how it is allowed.

Change I also managed to get a basic example of working with Iron Router.

 ImageController = RouteController.extend({ run: function() { var f = fs.readFileSync("/path/to/image.png"); var res = this.response; res.writeHead(200, { "content-type": "image/png" }); res.write(f); res.end(); } }); Router.map(function() { Router.route("images", { path: "/images/image.png", where: "server", controller: ImageController // Note - cannot use string here - Iron Router has a dependency on window }); }); 
+4
source share
2 answers

You can write the response code, as in any node application, using middleware:

 WebApp.connectHandlers.stack.splice (0, 0, { route: '/path/to/the/file', handle: function(req, res, next) { res.writeHead(200, { 'Content-Type': ...ITEM TYPE... , }); res.write( ...ITEM DATA... ); res.end(); }, }); 
0
source

You can use filepicker. In filepicker, uploaded images are saved in a bucket (cloud) and return the URL of this image. You can save url in your mongo database. and when you want to use this image just use <img src="{{saveurl}}" > . For more help see the documentation https://developers.inkfilepicker.com/docs/web/

0
source

Source: https://habr.com/ru/post/1501825/


All Articles