Open routes/upload.js. It's fairly simple:
const express = require('express');
const formidable = require('formidable');
const router = express.Router();
const fs = require('fs');
router.post('/', (req, res, next) => {
const form = new formidable.IncomingForm().parse(req)
.on('fileBegin', (name, file) => {
file.path = __dirname + '/../public/images/' + file.name
})
.on('file', () => {
res.sendStatus(200)
})
});
module.exports = router;
To make our lives a little easier, we're using a form handler package called Formidable. When a POST request comes through to the /upload endpoint, it's going to run this code. When a form is received via Ajax, our promises are listening for files and will trigger the fileBegin and file events that will write the file to disk and then signal success, respectively. This is the method that our upload form used...