uploadController.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. }).single('file')
  19. uploadsController.upload = function(req, res, next){
  20. if(config.TOKEN !== '')
  21. if(req.headers.auth !== config.TOKEN)
  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. db.table('files').insert({
  33. file: req.file.filename,
  34. original: req.file.originalname,
  35. type: req.file.mimetype,
  36. size: req.file.size,
  37. ip: req.ip,
  38. galleryid: gallery,
  39. created_at: Math.floor(Date.now() / 1000)
  40. }).then(() => {
  41. return res.json({
  42. success: true,
  43. files: [
  44. {
  45. name: req.file.filename,
  46. size: req.file.size,
  47. url: config.basedomain + req.file.filename
  48. }
  49. ]
  50. })
  51. })
  52. })
  53. }
  54. uploadsController.list = function(req, res){
  55. if(config.TOKEN !== '')
  56. if(req.headers.auth !== config.TOKEN)
  57. return res.status(401).send('not-authorized')
  58. db.table('files').then((files) => {
  59. for(let file of files){
  60. file.file = config.basedomain + config.uploads.prefix + file.file
  61. file.ext = file.file.split('.').pop()
  62. file.date = new Date(file.created_at * 1000)
  63. 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()
  64. }
  65. return res.json(files)
  66. })
  67. }
  68. module.exports = uploadsController