Created
October 1, 2019 05:10
-
-
Save fahmifan/d9094c21a64ba5beffcc8eff39ef041d to your computer and use it in GitHub Desktop.
Upload file using multer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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