简体   繁体   中英

How to serve images from a private folder from Node.js to a website/application in a restful manner?

Hey how can I serve images from a private folder from Node.js to a website/application in a restful manner? I currently been saving the images in an img folder that is in the public folder, while saving the id of the image in the db and when a user goes to his profile, his picture is loaded by looking up the picture id and setting the path of the picture to public > img > id, however this is not good for two reasons...

One: The picture is public available for anyone... Two: This means all pictures are loaded as the pictures are in the website's resources...

There are probably more problems as well... but I am trying to figure out how to serve it if I changed the path of the images to a private folder, how do I allow a website to ask for a user's profile picture and be able to serve it back or if a user going to his profile on an android application?

Also, should the images being server, be static or something, I do plan on using Nginx in the future...

Update - For Express 4.x using res.sendFile

app.get('/user/:uid/photos/:file', function (req, res) {
  var uid = req.params.uid
  var file = req.params.file

  req.user.mayViewFilesFrom(uid, function (yes) {
    if (yes) {
      res.sendFile('/uploads/' + uid + '/' + file)
    } else {
      res.status(403).send("Sorry! You can't see that.")
    }
  })
})

Security against malicious up-paths /../ is included .

Old

  var fs = require('fs')
    
    function(req, res) {
      var id = req.param('id')
      fs.exists('/private/img/'+id, function(exists) {
        if(exists) res.sendfile('/private/img/'+id)
        else res.end('err')
      })
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM