1
0
mirror of https://github.com/Foltik/Shimapan synced 2024-11-10 23:53:31 -05:00
shimapan/app/routes/upload.js

55 lines
1.3 KiB
JavaScript
Raw Normal View History

2017-10-09 22:01:02 -04:00
var express = require('express');
var router = express.Router();
2017-10-11 10:15:19 -04:00
var mongoose = require('mongoose');
2017-10-09 22:01:02 -04:00
var Upload = require('../models/Upload.js');
2017-10-11 10:15:19 -04:00
var multer = require('multer');
2017-10-09 22:01:02 -04:00
var dest = multer({dest: 'uploads/'});
function fileNameExists(name) {
Upload.count({name: name}, function(err, count) {
return count !== 0;
});
}
function genFileName() {
var charset = "abcdefghijklmnopqrstuvwxyz";
do {
var chars = [];
for (var i = 0; i < 6; i++)
chars.push(charset.charAt(Math.floor(Math.random() * charset.length)));
} while (fileNameExists(chars.join('')));
return chars.join('');
}
router.post('/', dest.single('file'), function(req, res) {
2017-10-13 16:16:48 -04:00
if (req.payload.scope.indexOf('file.upload') === -1) {
res.status(403).json({'message': 'Permission error.'});
return;
}
// Size must be below 128 Megabytes (1024*1024*128 Bytes)
if (req.file.size >= 134217728) {
res.status(413).json({'message': 'File too large.'});
2017-10-13 16:16:48 -04:00
return;
}
2017-10-11 10:15:19 -04:00
2017-10-09 22:01:02 -04:00
var entry = {
name: genFileName(),
oname: req.file.originalname,
created: Date.now(),
file: req.file
};
Upload.create(entry, function(err, next) {
if (err) {
next(err);
} else {
res.send(entry);
}
});
});
module.exports = router;