const express = require('express');
const multer = require('multer');
const teachersController = require('../controllers/teachers_controller')

const router = express.Router();

router.get('/', teachersController.getAll);
router.put('/:id', multer().single('teacherPhoto'), teachersController.addPhotoUrl);
router.get('/:id', teachersController.getOneTeacher);
router.get('/:id/classes', teachersController.getTeachersClasses);

module.exports = router;
Example #2
0
File: api.js Project: vjjd/mitomin
'use strict';

let  multer = require('multer');
let  worker = require('./worker');
let express = require('express');
let consts  = require('./constants');

let router = express.Router();
let upload = multer({ dest: 'uploads' });

router.post('/tasks', upload.any(), (req, res) => {
    let tasks = req.files.map(file => {
        return {
            label: file.originalname,
            id: file.filename,
            bodyName: file.originalname.replace(/\.?\w+$/g, ''),
            hash: '',
            type: consts.tTypes.upload.file.unhashed,
            status: consts.tStatus.pending
        }
    });
    
    tasks.forEach(worker.addTask);

    res.json({
        upload: true,
        tasks
    });
});

router.get('/tasks/:id', (req, res) => {
Example #3
0
var express=require('express');
var multer=require('multer');
var app=express();
app.use(multer({ dest: './uploads/'}));
var bodyParser=require('body-parser');
var http=require('http');
var server=http.createServer(app);
var fs=require('fs');

var cloudinary=require('cloudinary');

var application_root=__dirname,
    path=require('path');


app.use(bodyParser());
app.use(express.static(application_root));



cloudinary.config({
 cloud_name: 'your_cloud_name',
 api_key: 'your_api_key',
 api_secret: 'your_api_secret'
})


app.get('/',function(req,res)
{
 res.sendfile('index.html');
});
Example #4
0
router.put('/:agenda_id', function(req, res, next) {
	var storage = multer.diskStorage({
	destination: '../uploads/',
	filename: function (req, file, cb) {
	    crypto.pseudoRandomBytes(16, function (err, raw) {
	      if (err) return cb(err)

	      cb(null, raw.toString('hex') + path.extname(file.originalname))
	    })
  	}
	});
	var upload = multer({ storage: storage }).single('lampiran');
	var db = req.db;
	var status = "Belum dibaca";
	var is_delete = "0";
	var collection = db.get('agenda');	
	
	upload(req, res, function(err){
		var no_surat = req.body.no_surat;
		var no_agenda = req.body.no_agenda;
		var tanggal_surat = req.body.tanggal_surat;
		var tanggal_diterima = req.body.tanggal_diterima;
		var pengirim = req.body.pengirim;
		var perihal = req.body.perihal;
		var penerima = req.body.penerima;
		var jenis_surat = req.body.jenis_surat;
		var lampiran = "";
		if(err){
		    res.json({
			  "results": {
			    "success": false,
			    "message": "Gagal menambahkan data agenda,"+ err
			  }
			}); 
	    }
		collection.find({_id: req.params.agenda_id},{},function(err, docs){
		if (err) {
			res.json({
			  "results": {
			    "success": false,
			    "message": "Gagal mengubah data Agenda dengan id"+ req.params.agenda_id +","+ err
			  }
			});
		}
		else {
			lampiran = docs[0].lampiran;
			if(typeof(req.file)!='undefined') {
				fs.unlinkSync('..'+lampiran);
				console.log('successfully deleted ..'+lampiran);
				lampiran = "/uploads/"+req.file.filename;
			}
			collection.update(req.params.agenda_id, {
				"no_surat" : no_surat,
				"no_agenda" : no_agenda,
				"tanggal_surat" : new Date(tanggal_surat),
				"tanggal_diterima" : new Date(tanggal_diterima),
				"pengirim" : pengirim,
				"perihal" : perihal,
				"penerima" : penerima,
				"jenis_surat" : jenis_surat,
				"lampiran" : lampiran,
				"status" : status,
				"updatedAt": new Date(),
				"is_delete" : is_delete
			}, function (err, doc) {
				if (err) {
					res.json({
					  "results": {
					    "success": false,
					    "message": "Gagal mengubah data Agenda dengan id"+ req.params.agenda_id +","+ err
					  }
					});
				}
				else {
					res.json({
					  "results": {
					    "success": true,
					    "message": "Data agenda berhasil diubah"
					  }
					});
				}
			});
		}	
	}
);



	    
  	});
});
Example #5
0
router.post('/:ask', function(req, res, next) {
  switch(req.params.ask) {
      case 'add_tenant':
            res.setHeader('Content-Type', 'application/json');
            saveTenant(req.body, function(result) {
                if (result.status == SUCCESS) {
                    res.send({status:SUCCESS, tenant:req.body.domain});
                }
                else {
                    res.send({status:FAIL, tenant: req.body.domain, message:result.message});
                }
                res.end();
            })
            break;
      case 'add_fiddle':
            res.setHeader('Content-Type', 'application/json');
            var fiddle = {};
            var storage =   multer.diskStorage({
              destination: function (req, file, cb) {
                  var dest = __dirname+'/../public/fiddles/'+req.body.name;
                  if (!fs.existsSync(dest)){
                      fs.mkdirSync(dest);
                  }
                  cb(null,dest);
              },
              filename: function (req, file, cb) {
                  var type = file.originalname.split('.').pop();
                  type = type == "js" ? "script" : type;
                  fiddle[type] = file.originalname;
                  cb(null, file.originalname);
              }
            });
            var upload = multer({storage:storage}).array('fiddle_files');
            upload(req,res,function(err) {
              if(err) {
                  res.send({status:FAIL, fiddle:req.body.name, message:err});
                  res.end();
              }
              else {
                  fiddle['name'] = req.body.name;
                  if (!fiddle.html) {
                      res.send({status:FAIL, fiddle:req.body.name, message: "html file is missing"});
                      res.end();
                  }
                  else
                      db.fiddles.update({"name":fiddle.name},fiddle, {upsert:true}, function(err,value) {
                          if (!err) {
                              res.send({status:SUCCESS, fiddle:req.body.name});
                              res.end();
                          }
                          else {
                              res.send({status:FAIL, fiddle:req.body.name, message:err});
                              res.end();
                          }
                      });
              }
            });
            break;
      default:
            if (next) {
                var err = new Error('Not Found');
                err.status = 404;
                next(err);
            }
            break;
  }
});
Example #6
0
var express = require('express');
var router = express.Router();
var watermarkHelper = require('../helpers/watermarkHelper.js');
var Promise = require('bluebird');
var models = require('../models');
var queueHelper = require('../helpers/queueHelper.js');
var shopChecker = require('../middlewares/shopChecker.js');
var fs = require('fs');
var imageHelper = require('../helpers/imageHelper.js');
var multer = require('multer');
var upload = multer({
  dest: 'upload/'
})
module.exports = router;

process.on("unhandledRejection", function(reason, promise) {
    console.log(reason, promise);
});

process.on("rejectionHandled", function(promise) {
    console.log(promise);
});

router.get('/', shopChecker, (req, res) => {
  return getPreviewDefaultData(req)
    .then(defaultData => {
      return res.render('admin/index', {
        form: defaultData.form,
        fontNames: defaultData.fontNames,
        previewImageUrl: defaultData.previewImageUrl,
        shop: req.data.shop
module.exports = (PORT) => {

  const wineData = path.join(__dirname, 'src/data/wine.json');
  const categoryData = path.join(__dirname, 'src/data/categories.json');
  const regionData = path.join(__dirname, 'src/data/region.json');
  const imagesData = path.join(__dirname, 'src/data/images.json');

  const app = express();
  const jsonParser = bodyParser.json();
  let token;
  const nuid = 'demo';
  const ssw = 'demopassword'

  app.use(statics(__dirname + '/uploads'));

  app.use(serveStatic(__dirname + '/build'));
  app.use(jsonParser);
  app.use(bodyParser.urlencoded({extended: true}));

  // Additional middleware which will set headers that we need on each request.
  app.use(function (req, res, next) {
    // Set permissive CORS header - this allows this server to be used only as
    // an API server in conjunction with something like webpack-dev-server.
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

    // Disable caching
    res.setHeader('Cache-Control', 'no-cache');
    next();
  });

  crypto.randomBytes(48, function(err, buffer) {
    token = buffer.toString('hex');
  });

  // Login route
  app.post('/api/auth', jsonParser, function (req, res) {
    var post = req.body;
    if (post.username === nuid && post.password === ssw) {
      res.status(200);
      res.json({
        ok: true,
        token: token,
        expires: new Date(+new Date() + 1000 * 60 * 60 * 12)
      });

    } else {
      res.status(401);
      res.json({
        error: true
      });
    }
  });

  // Logout route
  app.get('/logout', function (req, res) {
    delete req.session.user_id;
    res.redirect('/login');
  });

  // Read datas
  app.get('/api/wines', function (req, res) {
    fs.readFile(wineData, function (err, data) {
      if (err) {
        console.error(err);
        process.exit(1);
      }
      res.json(JSON.parse(data));
    });
  })

  app.get('/api/categories', function (req, res) {
    fs.readFile(categoryData, function (err, data) {
      if (err) {
        console.error(err);
        process.exit(1);
      }
      res.json(JSON.parse(data));
    });
  })

  app.get('/api/regions', function (req, res) {
    fs.readFile(regionData, function (err, data) {
      if (err) {
        console.error(err);
        process.exit(1);
      } else {
        const regions = JSON.parse(data);
        res.json(regions);
      }
    });
  })

  app.get('/api/regions/:id', function (req, res) {
    fs.readFile(regionData, function (err, data) {
      if (err) {
        console.error(err);
        process.exit(1);
      } else {
        const regions = JSON.parse(data);
        res.json(_.find(regions, region => region.id === req.params.id));
      }
    });
  })

  app.get('/api/images', function (req, res) {
    fs.readFile(imagesData, function (err, data) {
      if (err) {
        console.error(err);
        process.exit(1);
      } else {
        const images = JSON.parse(data);
        res.json(images);
      }
    });
  })


  // Write datas
  app.post('/api/wines/:id', jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400)

    const id = req.params.id;
    const previousWines = JSON.parse(fs.readFileSync(wineData));
    const editedWine = _.find(previousWines, function(wine) { return wine.id == id });

    if (editedWine) {
      const index = _.indexOf(previousWines, _.find(previousWines, {id: id}));
      previousWines[index] = req.body;
      fs.writeFile(wineData, JSON.stringify(previousWines));

    } else {
      fs.writeFile(wineData, JSON.stringify([
        ...previousWines,
        req.body
      ]));
    }

    res.status(202);
    res.json(true);
    res.end("new wine posted");
  })


  app.post('/api/categories', jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400)
    console.log(req.body);

    const previousCat = JSON.parse(fs.readFileSync(categoriesData));
    if (_.find(previousCat, cat => cat.id === id)) {
      // update existing category
    } else {
      fs.writeFile(categoriesData, JSON.stringify([
        ...previousCat,
        req.body
      ]));
    }

    res.status(202);
    res.end("new category posted");
  })


  const storage = multer.diskStorage({
    destination: function (req, file, callback) {
      callback(null, path.join(__dirname, 'uploads'));
    },

    filename: function (req, file, callback) {
      callback(null, file.fieldname + '-' + Date.now());
    }
  });

  const upload = multer({ storage : storage});

  // Image upload
  app.post('/api/images', upload.single('photo'), function(req, res){
    console.log(req.file);
    return res.json(req.file.filename);
    upload(req, res, function(err) {
      if(err) {
        return res.end("Error uploading file.");
      }
      console.log(req) // I should see image array!
      res.end("msg form express: File is uploaded");
    });
  });

  app.delete('/api/wines/:id', jsonParser, function (req, res) {
    const previous = JSON.parse(fs.readFileSync(wineData));
    const id = req.params.id;
    const updated = _.filter(previous, (wine) => wine.id !== id);

    fs.writeFile(wineData, JSON.stringify(updated));
    res.json(true);
  })

  // Finally, listen to the port
  app.listen(PORT, function (err) {
    if (err) {
      console.log(err);
      return;
    }
    console.log('Express listening at ' + PORT);
  });
};
var express = require('express');
var app = express();
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

var developer = [
    {
        firstName: 'Alice', lastName: 'kumar', apps: [
            {name : 'Word'},{name : 'PowerPoint'},{name:'Excel'}
        ]
    },

    {
        firstName: 'alugonda', lastName: 'kumar', apps: [
              { name: 'Word' }, { name: 'PowerPoint' }, { name: 'Excel' }
        ]
    },

    {
        firstName: 'chris', lastName: 'kumar', apps: [
              { name: 'Word' }, { name: 'PowerPoint' }, { name: 'Excel' }
        ]
    },

    {
        firstName: 'jason', lastName: 'kumar', apps: [
Example #9
0
/**
 * express.static来设置本地静态文件css,js,img等
 * 将静态文件放到public目录下
 * app.use(express.static('public'))
 */

// express 上传文件
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var multer = require('multer');

app.use(express.static('public'));//静态文件
app.use(bodyParser.urlencoded({ extended: false }));//编码
app.use(multer({ dest: '/tmp/'}).array('image'));//上传文件

// 上传文件的html页面
app.get('/uploadfile.html',function(req,res){
  res.sendFile(__dirname + '/' + 'uploadfile.html');
});

// 上传到的位置
app.post('/file_upload',function(req,res){
  console.log(req.files[0]);//上传文件信息
  var des_file = __dirname + '/' + req.files[0].originalname;
  // 读取文件流
  fs.readFile(req.files[0].path , function(err,data){
    var response;
    if(err){
     console.log(err);
Example #10
0
const fs = require('fs')
const bytes = require('bytes')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const createKeyGenerator = require('./key-generator')

function checkApiKey (req, res, next) {
  if (req.get('X-API-KEY') === process.env.API_KEY) {
    return next()
  } else {
    res.sendStatus(403)
  }
}

function createUploadHandler (app, db, log, AWS) {
  const generateKey = createKeyGenerator(db)

  app.post('/', upload.single('file'), checkApiKey, (req, res, next) => {
    if (!req.file) {
      return res.sendStatus(400)
    }

    log.info(`Uploading image with size ${bytes(req.file.size)}`)

    let body = fs.createReadStream(req.file.path)

    generateKey((key) => {
      let s3obj = new AWS.S3({
        params: {
          Bucket: process.env.AWS_BUCKET,
          Key: key
Example #11
0
/* https://www.npmjs.com/package/multer-s3 */
var storage = multerS3({
	s3: s3,
	bucket: 'mygram',
	acl: 'public-read', // access control list (visibilidad de los archivos)
	metadata : function (req, file, cb) {
		cb(null, { fieldName: file.fieldname })
	},
	key: function (req, file, cb) {
		cb(null, +Date.now() + '.' + ext(file.originalname))
	}

})

// middleware de upload
var upload = multer({ storage: storage }).single('picture') /*le pasamos picture que es el atributo name que lleva el input detipo file en el form*/

var app = express();

/*
 * queremos que express sea capaz de hacer parse de peticions http que contengan un json,
 * de esta manera cualquier peticion que llegue con un json vamos a poder obtener el obj
 * json en el body de nuestro request de una manera ya serializada
 */
app.set(bodyParser.json())

/*
 * middleware para poder recibir los params del request que vienen desde un form que los
 * codifica la peticion http de manera diferente y le pasamos una property que necesita
 * por defecto y es que el obj que viene no va a ser extendido
 */
Example #12
0
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
//define routes 
var routes = require('./routes/index'); // homepage
var users = require('./routes/users'); // reg form and login form
//instantiate express object into app // core instance
var app = express();

// view engine setup : im using jade so use this
app.set('view engine', 'jade');
//current folder+join+string views
app.set('views', path.join(__dirname, 'views'));
//Handle File uploads
//all the upload destination is in a new folder called uploads
app.use(multer({dest:'./uploads'}).single('singleInputFileName'));
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));

//middleware register !
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//Handle Express Sessions
app.use(session({
  secret:'secret',
  saveUninitialized: true,
  resave:true
}));
//Passports
Example #13
0
  var storage = multer.diskStorage({
    //设置上传后文件路径,uploads文件夹会自动创建。
    destination: function (req, file, cb) {
      cb(null, path)
    },
    //给上传文件重命名,获取添加后缀名
    filename: function (req, file, cb) {
      var fileFormat = (file.originalname).split(".");
      cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
  });
  return storage ;
}

var uploadImg = multer({
  storage: setUploadPath("public/media/img")
}) ;

var uploadVideo = multer({
  storage: setUploadPath("public/media/video")
}) ;

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('uploadVideo');
});


router.post('/video',uploadVideo.single('av_file'),function(req,res,next){
  var data = {
    code:0,
Example #14
0
//     //connection.end();
//     //db.contactlist.insert(req.body, function(err, doc) {
//     //  res.json(doc);
//     //});
// });
var fileName;
var storage2 =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './public/img/uploads');
  },
  filename: function (req, file, callback) {
    fileName='userFoto-' + Date.now()+file.originalname.substring(file.originalname.lastIndexOf("."))
    callback(null, fileName);
  }
});
var upload2 = multer({ storage : storage2}).single('file');

// app.get('/',function(req,res){
//     res.sendFile(__dirname + "/index.html");
// });

app.post('/api/photo',function(req,res){
  upload2(req,res,function(err) {
    if(err) {
      return res.end("Error uploading file.");
    }
    var id=req.body.id;
    var imagePath="img/uploads/"+fileName ;
    var updateRecord = 'UPDATE ey_users SET AVATAR = ?  WHERE ID=?';
    connection.query(updateRecord, [imagePath,id  ], function (err, result) {
      if (err) throw err;
Example #15
0
    cb(null, 'uploads/');
  },
  filename: function(req, file, cb) {
    var getFileExt = function(fileName) {
      var fileExt = fileName.split(".");
      if (fileExt.length === 1 || (fileExt[0] === "" && fileExt.length === 2)) {
        return "";
      }
      return fileExt.pop();
    };
    cb(null, Date.now() + '.' + getFileExt(file.originalname));
  }
});

var multerUpload = multer({
  storage: storage
});
var uploadFile = multerUpload.single('userFile');

module.exports = function(app, File) {
  app.post('/upload', function(req, res) {
    uploadFile(req, res, function(err) {
      if (err) {
        // An error occurred when uploading 
        log.error(err);
      }
      // Everything went fine 
      var fileDetails = {
        name: req.file.originalname,
        size: req.file.size,
        date: new Date().toLocaleString(),
Example #16
0
var puntuaciones = require('./routes/puntuaciones');

// Jugada
var jugada = require('./routes/jugada');

// Error
var error = require('./routes/error');

// Mysql 
var connection  = require('express-myconnection'); 
var mysql = require('mysql');

// Subida de ficheros
var fs = require('fs');
var multer = require('multer');
var upload = multer({ dest: 'tmp/'}); 
var files_uploaded = require('./routes/files_uploaded');

// configuracion passport
require('./passport')(passport);

var app = express();



// all environments
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
Example #17
0
var http       = require('http').Server(app);
var gzippo     = require('gzippo');
var morgan     = require('morgan');
var bodyParser = require('body-parser');
var multer     = require('multer');
var mongoose   = require('mongoose');
var Room       = require('./models/room');
var Message    = require('./models/message');
var io         = require('socket.io')(http);
var md5        = require('blueimp-md5').md5;

mongoose.connect('mongodb://localhost/flux-react-chat');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer());

app.use(morgan('tiny'));
app.use(gzippo.staticGzip('' + __dirname));
app.use(function(err, req, res, next){
  console.error(err.stack);
  res.send(500, 'Something broke!');
});

var createUser = function(user) {
  var userName, userEmail, userImage;
  var date = Date.now();
  if (user.name) {
    userName = user.name;
  } else if (user.email){
    userName = user.email.split('@')[0];
Example #18
0
var User = require(process.cwd() + "/lib").User
var filter = require(process.cwd() + "/filter")
var fs = require("fs")
var checkNotLogin = require(process.cwd() + "/validate").checkNotLogin

//文件解析
var multer = require("multer");
var storage = multer.diskStorage({
    destination : function(req,file,cb){
        cb(null, process.cwd() + "/static/img/user/")
    },
    filename : function(req,file,cb){
        cb(null, Date.now() + file.originalname)
    }
})
var upload = multer({storage:storage})


exports.get = function(req, res, next) {
	var id = req.params.id
	User.findById(id)
		.then(function(data) {
			res.status(200).json(data)
		})
		.catch(function(err) {
			console.log(err)
			next(err)
		})
}

exports.post = [upload.single("avatar"), checkNotLogin, function(req, res, next) {
Example #19
0
// GET: videoViewerPage
router.get('/viewvideos', function(req, res) {
        res.sendfile(__dirname + '/public/viewvideos.html');
});

// POST: video upload route
// multer approach
var multer = require('multer');
app.use(multer({
	
	//Set dstination directory
	dest: path.resolve(__dirname, 'public', 'uploaded_videos'),
	
	//Rename file
	rename: function (fieldname, filename) {
		//Add the current date and time in ISO format, removing the last 'Z' character this usually
		//includes
		var dateNow = new Date();
	    return filename + "_" + dateNow.toISOString().slice(0,-1)
	}

}));

router.post('/web_video_upload', function(req, res) {
	res.send('Video Uploading');
	console.dir(req.files);
});

// GET: route to return list of upload videos 
router.get('/video_list', function(req, res) {
	// Get the path for the uploaded_video directory - in a real app the video list would likely be taken from 
Example #20
0
File: index.js Project: 3GA/relax
  secret: 'Is very secret',
  store: new MongoStore({mongooseConnection: mongoose.connection})
}));

// Passport
app.use(passport.initialize());
app.use(passport.session());

// Static files
app.use(express.static('./public'));
app.use(['favicon.ico', '/images*', '/media*', '/css*', '/fonts*', '/js*'], (req, res) => {
  res.status(404).end();
});

// Multer
app.use('/graphql', multer({dest: './uploads/'}).single('file'));

// GraphqQL server
app.use('/graphql', graphqlHTTP(req => ({
  schema: schema.getSchema(),
  rootValue: {
    isAuthenticated: req.isAuthenticated(),
    user: req.user,
    file: req.file
  },
  graphiql: true
})));

app.use(async (req, res, next) => {
  const settingsArr = await SettingModel
    .find({
Example #21
0
        }else{
            // remove the image from disk
            fs.unlink(path.join("public", req.body.product_image), function(err){
                if(err){
                    res.status(400).json({message: 'Image not removed, please try again.'});
                }else{
                    res.status(200).json({message: 'Image successfully deleted'});
                }
            });
        }
    });
});

// upload the file
var multer  = require('multer')
var upload = multer({ dest: 'public/uploads/' });
router.post('/file/upload', common.restrict, upload.single('upload_file'), function (req, res, next) {
	var fs = require('fs');
    var path = require('path');
	
	if(req.file){
		// check for upload select
		var upload_dir = path.join("public/uploads", req.body.directory);
		
        // Check directory and create (if needed)
        common.check_directory_sync(upload_dir);
		
		var file = req.file;
		var source = fs.createReadStream(file.path);
		var dest = fs.createWriteStream(path.join(upload_dir, file.originalname.replace(/ /g,"_")));
Example #22
0
	postsdb.get(req.params.postId, function(err, foundPost) {
		res.status(foundPost ? 200 : 404).json(foundPost);
	});
});

router.delete('/:postId', (req, res) => {
	postsdb.destroy(req.params.postId, req.query.rev, function(err, data) {
		res.status(200).send();
	});
});

router.get('/:postId/image', (req, res) => {
	postsdb.attachment.get(req.params.postId, 'IMAGE').pipe(res);
});

router.put('/:postId/image', multer().any(), (req, res, next) => {
	var imageFile = req.files[0];
	var buffer = imageFile.buffer;
	var mimetype = imageFile.mimetype;
	var fileName = imageFile.originalname;
	postsdb.get(req.params.postId, function(err, foundPost) {
		if (err) {
			next(err);
		} else {
			postsdb.attachment.insert(req.params.postId, 'IMAGE', buffer, mimetype, { rev : foundPost._rev }, (err, body) => {
				if (err) {
					return next(err);
				}
				res.status(200).json({});
			});
		}
Example #23
0
router.post('/', function(req, res) {
	var storage = multer.diskStorage({
	destination: '../uploads/',
	filename: function (req, file, cb) {
	    crypto.pseudoRandomBytes(16, function (err, raw) {
	      if (err) return cb(err)

	      cb(null, raw.toString('hex') + path.extname(file.originalname))
	    })
  	}
	});
	var upload = multer({ storage: storage }).single('lampiran');
	var db = req.db;
	var status = "Belum dibaca";
	var is_delete = "0";
	var collection = db.get('agenda');

	upload(req, res, function(err){
	    var no_surat = req.body.no_surat;
		var no_agenda = req.body.no_agenda;
		var tanggal_surat = req.body.tanggal_surat;
		var tanggal_diterima = req.body.tanggal_diterima;
		var pengirim = req.body.pengirim;
		var perihal = req.body.perihal;
		var penerima = req.body.penerima;
		var jenis_surat = req.body.jenis_surat;
		var lampiran = "/uploads/"+req.file.filename;
	    if(err){
		    res.json({
			  "results": {
			    "success": false,
			    "message": "Gagal menambahkan data agenda,"+ err
			  }
			}); 
	    }
    	collection.insert({
			"no_surat" : no_surat,
			"no_agenda" : no_agenda,
			"tanggal_surat" : new Date(tanggal_surat),
			"tanggal_diterima" : new Date(tanggal_diterima),
			"pengirim" : pengirim,
			"perihal" : perihal,
			"penerima" : penerima,
			"jenis_surat" : jenis_surat,
			"lampiran" : lampiran,
			"status" : status,
			"createdAt": new Date(),
			"updatedAt": new Date(),
			"is_delete" : is_delete
			}, function (err, doc) {
				if (err) {
					res.json({
					  "results": {
					    "success": false,
					    "message": "Gagal menambahkan data agenda,"+ err
					  }
					});
				}
				else {
					res.json({
					  "results": {
					    "success": true,
					    "message": "Data agenda berhasil ditambahkan"
					  }
					});
				}
		});
  	});
});
Example #24
0
var router = express.Router();
var storage = require('./storage');
var multer = require('multer');
var db = require('seraph')({
	server: process.env.SERVER_URL || 'http://localhost:7474/', // 'http://studionetdb.design-automation.net'
	user: process.env.DB_USER,
	pass: process.env.DB_PASS
});
var auth = require('./auth');
var glob = require('glob');
var path = require('path');

// POST: /uploads/avatar
// Upload a new profile picture
router.post('/avatar', auth.ensureAuthenticated, multer({
	storage: storage.avatarStorage
}).single('avatar'), function(req, res, next){

	// update avatar for user
	var query = [
		'MATCH (u:user) WHERE ID(u)=' + req.user.id,
		'WITH u',
		'SET u.avatar={avatarParam}',
		'RETURN u'
	].join('\n');

	var params = {
		avatarParam: '/uploads/users/' + req.user.nusOpenId + '/avatar'
	};
	
	db.query(query, params, function(error ,result){
module.exports=function(app,models) {

  var widgetModel = models.widgetModel;

  var multer = require('multer'); // npm install multer --save
  var upload = multer({ dest: __dirname+'/../../public/uploads' });
var widgets = [
  { "_id": "123", "widgetType": "HEADER", "pageId": "321", "size": 2, "text": "GIZMODO"},
  { "_id": "234", "widgetType": "HEADER", "pageId": "321", "size": 4, "text": "Lorem ipsum"},
  { "_id": "345", "widgetType": "IMAGE", "pageId": "321", "width": "100%",
    "url": "http://lorempixel.com/400/200/"},
  { "_id": "456", "widgetType": "HTML", "pageId": "321", "text": "<p>Lorem ipsum</p>"},
  { "_id": "567", "widgetType": "HEADER", "pageId": "321", "size": 4, "text": "Lorem ipsum"},
  { "_id": "678", "widgetType": "YOUTUBE", "pageId": "321", "width": "100%",
    "url": "https://youtu.be/AM2Ivdi9c4E" },
  { "_id": "789", "widgetType": "HTML", "pageId": "321", "text": "<p>Lorem ipsum</p>"}
];

  app.post("/api/page/:pageId/widget", createWidget);
  app.get("/api/page/:pageId/widget",findAllWidgetsForPage);
  app.get("/api/widget/:widgetId",findWidgetById);
  app.put("/api/widget/:widgetId",updateWidget);
  app.delete("/api/widget/:widgetId",deleteWidget);
  app.post("/api/upload", upload.single('myFile'), uploadImage);
  app.put("/api/page/:pageId/widget",reorderWidgets);

  function reorderWidgets(req,res)
  {
    var start = parseInt(req.query.start);
    var stop = parseInt(req.query.end);
    var pageId = req.params.pageId;
    //console.log([start,stop]);
    widgetModel.reorderWidgets(start,stop,pageId)
      .then(function(stats)
        {
          res.send(200);
        },
        function(error)
        {
          res.statusCode.send(404);
        });

  }


  function uploadImage(req, res) {
    var widgetId      = req.body.widgetId;
    var pageId      = req.body.pageId;
    var userId      = req.body.userId;
    var websiteId      = req.body.websiteId;
    var width         = req.body.width;
    var myFile        = req.file;

    if(myFile === null)
    {
      res.redirect("/assignment/#/user/"+userId+"/website/"+websiteId+"/page/"+pageId+"/widget/"+widgetId);
      return;
    }

    var originalname  = myFile.originalname; // file name on user's computer
    var filename      = myFile.filename;     // new file name in upload folder
    var path          = myFile.path;         // full path of uploaded file
    var destination   = myFile.destination;  // folder where file is saved to
    var size          = myFile.size;
    var mimetype      = myFile.mimetype;

    var widget =
    {
      url:"/uploads/"+filename
    };

    widgetModel
      .updateWidget(widgetId,widget)
      .then(function(stats)
        {
          res.send(200);
        },
        function(error)
        {
          res.statusCode.send(404);
        })
    //for(var i in widgets)
    //{
    //  if(widgets[i]._id===widgetId)
    //  {
    //    widgets[i].url="/uploads/"+filename;
    //  }
    //}

    res.redirect("/assignment/#/user/"+userId+"/website/"+websiteId+"/page/"+pageId+"/widget/"+widgetId);
  }

  //-------------------------delete widget--------------------
  function deleteWidget(req,res)
  {
    var widgetId = req.params.widgetId;
    var pageId=req.query.pageId;
    var widgetNumber=req.query.widgetNumber;
    widgetModel
      .updateDeletedWidget(pageId,widgetNumber)
      .then(function(widgets)
    {

    widgetModel
      .deleteWidget(widgetId,widgets)
      .then(function(stats)
      {
        res.send(200);
      },
      function(error) {
        res.statusCode.send(error);
      });
    },function(error)
      {
        res.statusCode.send(error);
      });




    //for(var i in widgets)
    //{
    //  if(widgetId===widgets[i]._id) {
    //    widgets.splice(i, 1);
    //   res.send(200);
    //  }
    //}
    //res.send(400);
  }

  //---------------update widget----------------------------

  function updateWidget(req,res)
  {
    var widgetId = req.params.widgetId;
    var widget = req.body;

    widgetModel
      .updateWidget(widgetId,widget)
      .then(function(stats)
        {
          res.send(200);
        },
        function(error)
        {
          res.statusCode.send(404);
        })

    //for (var i in widgets) {
    //  if (widgets[i]._id === widgetId ) {
    //    switch (widgets[i].widgetType) {
    //      case "HEADER":
    //        widgets[i].size = widget.size;
    //        widgets[i].text = widget.text;
    //        res.send(200);
    //        break;
    //
    //      case "IMAGE":
    //        console.log("in image");
    //        widgets[i].width = widget.width;
    //        widgets[i].url = widget.url;
    //        res.send(200);
    //        break;
    //      case "YOUTUBE":
    //        widgets[i].width = widget.width;
    //        widgets[i].url = widget.url;
    //        res.send(200);
    //        break;
    //
    //
    //    }
    //
    //  }
    //}
  }



  //---------------------find all widgets for a page-------------------

function findAllWidgetsForPage(req,res)
{
  var pageId = req.params.pageId;

widgetModel
  .findAllWidgetsForPage(pageId)
  .then(function(widgets)
  {
    res.send(widgets);
  },function(error){
    res.statusCode(400).send(error);
  })

 // var resultSet=[];
 // for(var i in widgets)
 // {
 //   if(widgets[i].pageId===pageId)
 //   {
 //     resultSet.push(widgets[i]);
 //   }
 //
 // }
 //res.send(resultSet);

}

  //--------------------create Widget-------------------------

  function createWidget(req,res)
  {
    var widget = req.body;

    widgetModel
      .createWidget(widget)
      .then(function(widget)
        {
          res.send(widget);
        },
        function(error)
        {
          res.statusCode(400).send(error);
        });
    //widgets.push(newWidget);
    //res.send(newWidget);

  }

  //----------------------------find widget by id----------------------

  function findWidgetById(req,res)
  {
    var widgetId = req.params.widgetId;

    widgetModel
      .findWidgetById(widgetId)
      .then(function(widget)
  {
    res.send(widget);
  },
    function(error)
    {
      res.statusCode(400).send(error);
    });
    //for(var i in widgets)
    //{
    //  if(widgets[i]._id===widgetId)
    //  {
    //    res.send(widgets[i]);
    //    return;
    //  }
    //}
    //res.send({});
  }

//--------------------------count widgets------------------------

  function countWidgetByPageId(req,res)
  {
    var pageId = req.params.pageId;

    widgetModel
      .countWidgetByPageId(pageId)
      .then(function(widgets)
      {
        console.log(widgets);
        res.send(widgets);
      },function(error){
        res.statusCode(400).send(error);
      })
  }









}
Example #26
0
app.use(methodOverride());

var sessionSecret = config.get('sessionSecret');
if(sessionSecret.indexOf('please')===0) {
  console.error('warning:', sessionSecret);
}
app.use(session({
  name: 'misdirection.sid',
  resave: true,
  saveUninitialized: true,
  secret: sessionSecret
}));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer()); // Middleware for handling `multipart/form-data`.

if ('development' == app.get('env')) {
  app.use(morgan('dev'));
  app.use(errorHandler());
  app.use(config.get('controlpanel:path'), express.static(path.join(__dirname, 'public')));
}

exports.config = config;
exports.server = app;
exports.redis = db;

require('./routes/controlpanel').route(app);

app.use(function(req, res) {
  directions.find(req.path, function(err, info) {
Example #27
0
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.js');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var multer = require('multer');
var upload = multer({dest: __dirname + '/prod/uploads'});

var port = process.env.PORT || 8080;
var app = express();

app.use(express.static(__dirname + '/prod/dist/'));
app.use(express.static(__dirname + '/prod/'));
//for uploads
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*', function response(req, res) {
  res.sendFile(path.join(__dirname, 'prod/dist/index.html'));
});
app.post('/admin/upload-image', upload.single('file'), function(req,res,next){
  var filetype = res.req.file.mimetype.split('/')[1];
  res.json({"filename": res.req.file.filename+"." + filetype});
});

app.post('/contact', function(req, res){
  var transporter = nodemailer.createTransport('smtps://contact@emmabacani.com:EmmaLopezBacani85!@mail.privateemail.com');

  // setup e-mail data with unicode symbols
  var mailOptions = {
      from: 'contact@emmabacani.com',
Example #28
0
// development only
if (env === 'development') {
  // app.use(express.errorHandler());
}

// production only
if (env === 'production') {
  // TODO
}

var multerForImage = multer({ dest: 'public/uploads/temp/image',
  rename: function (fieldname, filename) {
    return filename;
  },
  onFileUploadStart: function (file) {
    console.log(file.originalname + ' is starting ...')
  },
  onFileUploadComplete: function (file) {
    console.log(file.originalname + ' uploaded to  ' + file.path)
  }
});

var multerForPackage = multer({ dest: 'public/uploads/temp/package',
  rename: function (fieldname, filename) {
    return filename;
  },
  onFileUploadStart: function (file) {
    console.log(file.originalname + ' is starting ...')
  },
  onFileUploadComplete: function (file) {
    console.log(file.originalname + ' uploaded to  ' + file.path)
Example #29
0
var express = require('express');
var multer = require('multer');

var UPLOAD_LIMIT_MB = 5;

var storage = multer.memoryStorage();
var upload = multer({
  storage: storage,
  limits: {
    fileSize: UPLOAD_LIMIT_MB * 1024 * 1024
  }
}).single('file');

var port = +process.env.PORT || 8080;
var app = express();

app.post('/api/upload', function(req, res) {
  upload(req, res, function(err)  {
    if(err) {
      return res.json({error: 'Exceeded file limit size of ' + UPLOAD_LIMIT_MB
        + ' MB.'});
    }
    res.json({size: req.file.size});
  });
});

app.use(express.static('public'));

app.listen(port);
Example #30
0
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})

var storageParent = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './'+config.baseuploadPath+config.parentsUploadDir)
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})

var studentUpload = multer({ storage: storage }) // students photo uploads location.
var parentUpload=multer({storage:storageParent}) // parents photo uploads location.

// application Required controllers starts from here.

/**
* URL: http://localhost:3000/api/verifyStudent/studentcode
* METHOD: GET
* Here, studentcode is the request param.
* this url verify the student against db and returns student data as response.
*/
router.get('/verifyStudent/:studentcode',function(req,resp, next){
	var query={sec_code:req.params.studentcode};
	console.log(query);
	studentService.verifyStudent(query,function(err,result){
		if(err){