Skip to content

Instantly share code, notes, and snippets.

@fahmifan
Created October 1, 2019 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fahmifan/d9094c21a64ba5beffcc8eff39ef041d to your computer and use it in GitHub Desktop.
Save fahmifan/d9094c21a64ba5beffcc8eff39ef041d to your computer and use it in GitHub Desktop.
Upload file using multer
const path = require('path')
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser')
const multer = require('multer');
const crypto = require('crypto');
const db = require('./db/db.json')
const port = process.env.PORT || 3000
const host = process.env.PORT || 'localhost'
const baseURL = `http://${host}:${port}`
const app = express()
// create application/json parser
app.use(bodyParser.json({ type: 'application/json' }))
// serve www
app.use('/', express.static(path.join(__dirname, 'www')))
// serve upload to access uploaded
app.use('/upload', express.static(path.join(__dirname, 'upload')))
// serve upload middleware
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'upload')
},
filename: function (req, file, cb) {
const name = file.fieldname + Date.now()
const hashed = crypto.createHash('md5').update(name ).digest("hex");
cb(null, hashed + path.extname(file.originalname))
}
})
const upload = multer({ storage: storage })
app.get('/ping', (req, res) => res.status(200).json({ping: "pong"}))
app.post('/api/users', (req, res) => {
// get body payload
const { name, email, npm, fotoURL } = req.body
const id = (new Date()).getTime()
const user = { id, name, email, npm, fotoURL }
// save user to db
db.users.push(user)
return res.status(200).json(user)
})
app.post('/api/save/file', upload.single('biodata'), (req, res) => {
const file = req.file
if (!file) return res.status(400).json({"error": "not a file"})
// save file path to db files
db.files.push({
id: file.filename,
path: `/upload/${file.filename}`
})
res.status(200).json({ "path": `${baseURL}/upload/${file.filename}` })
})
// perists db on terminate
process.on('SIGINT', function() {
console.log("\nsave to db...");
fs.writeFileSync(path.join('db', 'db.json'), JSON.stringify(db, undefined, 2))
process.exit();
});
app
.listen(port, () => console.log(`listening at :${port}`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment