uploadController.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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({ error: err })
  28. }
  29. db.table('files').insert({
  30. file: req.file.filename,
  31. galleryid: gallery
  32. }).then(() => {
  33. return res.json({
  34. 'url': config.basedomain + req.file.filename
  35. })
  36. })
  37. })
  38. }
  39. module.exports = uploadsController