//routes/admin/upload.js
//npm install multer
import path from 'path'
import express from 'express'
const uploadRoute = express.Router()
uploadRoute.get('/',async function(req,res){
if(req.session.user){
const module = await import('../../controllers/admin/upload/get.js')
module.default(req,res)
}else{
res.redirect('/admin/login')
}
})
import multer from 'multer'
const __dirname = path.resolve()
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, 'public/uploads/'))
},
filename: function (req, file, cb) {
const id = Date.now() + Math.round(Math.random() * 1E9).toString()
cb(null, id + '-' + file.originalname)
}
})
const upload = multer({storage: storage})
uploadRoute.post('/',upload.single("uploadFile"),async function(req,res,next){
if(req.session.user){
const module = await import('../../controllers/admin/upload/read.js')
module.default(req,res,next)
}else{
res.redirect('/admin/login')
}
})
export default uploadRoute
//controllers/admin/upload/read.js
import settings from '../../../settings.js'
let mySettings = JSON.parse(JSON.stringify(settings))
export default (req,res,next)=>{
const file = req.file
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
mySettings.pageTitle = 'ទំព័រ Upload'
mySettings.route = '/admin/upload'
mySettings.fileUrl = file.filename
res.render('base',{data:mySettings})
}
<!--views/admin/upload.ejs-->
<link href="/styles/admin/upload.css" rel="stylesheet"></link>
<div class='Upload'>
<form action='/admin/upload' method='post' enctype="multipart/form-data">
<input type='file' name='uploadFile' required />
<input type='text' value='<%= data.fileUrl %>'
placeholder='តំណរភ្ជាប់ឯកសារនៅលើ Server' />
<input type='submit' value='បញ្ជូនទិន្នន័យ' />
</form>
</div>