uploadController.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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.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. let gallery = req.headers.gallery
  21. if(!config.privacy.public)
  22. if(!config.privacy.IPs.includes(req.ip)) return res.status(401).send('Not Authorized!')
  23. upload(req, res, function (err) {
  24. if (err) {
  25. console.error(err)
  26. return res.json({ error: err })
  27. }
  28. db.table('files').insert({
  29. file: req.file.filename,
  30. galleryid: gallery
  31. }).then(() => {
  32. res.json({
  33. 'filename': req.file.filename
  34. })
  35. })
  36. })
  37. }
  38. module.exports = uploadsController