There are many packages that could be used to upload pictures to the website. Among those packages, multer is very popular among Express.js user. We can download and install this package by writing on Terminal window as below:
npm install multer
// routes/admin/upload.js
// npm install multer
import path from 'path'
import express from 'express'
const uploadRoute = express.Router()
import upload from '../../controller/admin/upload.js'
uploadRoute.get('/',async function(req,res){
if(req.session.user){
upload.getItem(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, 'static/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){
upload.postItem(req,res)
}else{
res.redirect('/admin/login')
}
})
export default uploadRoute
// controller/admin/upload.js
import config from '../../config.js'
class Upload{
constructor(){
(async () => {
this.config = await config()
})()
}
async getItem(req,res){
this.config.pageTitle = 'ទំព័រ Upload'
this.config.route = '/admin/upload'
res.render('base',{data:this.config})
}
async postItem(req,res){
const file = req.file
if(!file){
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
this.config.pageTitle = 'ទំព័រ Upload'
this.config.route = '/admin/upload'
this.config.fileUrl = '/uploads/' + file.filename
res.render('base',{data:this.config})
}
}
export default await new Upload()
<!--views/admin/upload.ejs-->
<link href="/styles/admin/upload.css" rel="stylesheet"></link>
<div class='Upload'>
<% if(data.fileUrl){ %>
<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>
<% delete data.fileUrl %>
<% }else{ %>
<form action='/admin/upload' method='post' enctype="multipart/form-data">
<input type='file' name='uploadFile' required />
<input type='text' placeholder='តំណរភ្ជាប់ឯកសារនៅលើ Server' />
<input type='submit' value='បញ្ជូនទិន្នន័យ' />
</form>
<% } %>
</div>