uploadController.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. const path = require('path')
  2. const config = require('../config.js')
  3. const multer = require('multer')
  4. const randomstring = require('randomstring')
  5. const db = require('knex')(config.database)
  6. let uploadsController = {}
  7. const storage = multer.diskStorage({
  8. destination: function (req, file, cb) {
  9. cb(null, './' + config.uploads.folder + '/')
  10. },
  11. filename: function (req, file, cb) {
  12. cb(null, randomstring.generate(config.uploads.fileLength) + path.extname(file.originalname))
  13. }
  14. })
  15. const upload = multer({
  16. storage: storage,
  17. limits: { fileSize: config.uploads.maxsize }
  18. }).array('files[]')
  19. uploadsController.upload = function(req, res, next){
  20. if(config.TOKEN === true)
  21. if(req.headers.auth !== config.clientToken)
  22. return res.status(401).send('not-authorized')
  23. let gallery = req.headers.gallery
  24. upload(req, res, function (err) {
  25. if (err) {
  26. console.error(err)
  27. return res.json({
  28. success: false,
  29. description: err
  30. })
  31. }
  32. let files = []
  33. req.files.forEach(function(file) {
  34. files.push({
  35. name: file.filename,
  36. original: file.originalname,
  37. type: file.mimetype,
  38. size: file.size,
  39. ip: req.ip,
  40. galleryid: gallery,
  41. created_at: Math.floor(Date.now() / 1000)
  42. })
  43. })
  44. db.table('files').insert(files).then(() => {
  45. res.json({
  46. success: true,
  47. files: files.map(file => {
  48. return {
  49. name: file.name,
  50. size: file.size,
  51. url: config.basedomain + file.name
  52. }
  53. })
  54. })
  55. })
  56. })
  57. }
  58. uploadsController.list = function(req, res){
  59. if(config.TOKEN === true)
  60. if(req.headers.auth !== config.clientToken)
  61. return res.status(401).send('not-authorized')
  62. db.table('files').then((files) => {
  63. for(let file of files){
  64. file.file = config.basedomain + config.uploads.prefix + file.name
  65. file.ext = file.name.split('.').pop()
  66. file.date = new Date(file.created_at * 1000)
  67. file.date = file.date.getFullYear() + '-' + file.date.getMonth() + '-' + file.date.getDate() + ' ' + (file.date.getHours() < 10 ? '0' : '') + file.date.getHours() + ':' + (file.date.getMinutes() < 10 ? '0' : '') + file.date.getMinutes() + ':' + (file.date.getSeconds() < 10 ? '0' : '') + file.date.getSeconds()
  68. }
  69. return res.json(files)
  70. })
  71. }
  72. module.exports = uploadsController