Posted By

bernicestockstill on 05/21/19


Tagged


Versions (?)

Image server snippet


 / Published in: JavaScript
 

Short snippet

  1. var express = require('express');
  2. var app = express();
  3. var path = require('path');
  4. var fs = require('fs');
  5. var dateFormat = require('dateformat');
  6. var jimp = require("jimp");
  7.  
  8. var uploadDir = 'public/uploads';
  9. app.set('view engine', 'pug');
  10. app.use(express.static('public'));
  11.  
  12. app.get('/images', (req, res) => {
  13. let images = getImagesFromDir(path.join(__dirname, 'public/uploads'));
  14. res.render('index', { title: 'Camera Trap Image Server', images: images })
  15. });
  16.  
  17.  
  18. function getImagesFromDir(dirPath) {
  19. let allImages = [];
  20.  
  21. let files = fs.readdirSync(dirPath);
  22.  
  23. for (file of files) {
  24. let fileLocation = path.join(dirPath, file);
  25. var stat = fs.statSync(fileLocation);
  26. if (stat && stat.isDirectory()) {
  27. getImagesFromDir(fileLocation); // process sub directories
  28. } else if (stat && stat.isFile() && ['.jpg', '.png'].indexOf(path.extname(fileLocation)) != -1) {
  29. allImages.push('uploads/'+file);
  30. }
  31. }
  32. return allImages;
  33. }
  34.  
  35.  
  36.  
  37.  
  38. app.post('/upload', function(req, res){
  39. var d = new Date()
  40. var filename = dateFormat(new Date(), "mm-dd-yyyy_HH_MM_ss") + ".jpg";
  41. filename = path.join(__dirname, uploadDir + '/' + filename);
  42. var f = fs.createWriteStream(filename);
  43. req.on('data', function(chunk) {
  44. f.write(chunk);
  45. }).on('end', function() {
  46. f.end();
  47.  
  48. // rotate image 180 degrees because camera is mounted upside-down
  49. jimp.read(filename, function (err, image) {
  50. image.rotate(180)
  51. .write(filename);
  52. }).catch(function (err) {
  53. console.log("error: " + err);
  54. });
  55.  
  56. console.log("saved " + filename);
  57. res.status(200).end("OK");
  58. });
  59.  
  60. });
  61.  
  62. var server = app.listen(8000, function(){
  63. console.log('Server listening on port 8000');
  64. });

Report this snippet  

You need to login to post a comment.