1// make this a middleware function,
2// then put it on the route like you used jwt,
3// then get the value with req.users.
4
5const { IncomingForm } = require('formidable')
6const { resolve } = require('path')
7const { existsSync, writeFileSync } = require('fs')
8
9module.exports = (req, res, next) => {
10 const form = new IncomingForm({
11 maxFileSize: 1 * 1024 * 1024,
12 keepExtensions: true
13 })
14
15 form.parse(req, (error, fields, file) => {
16 if (error) return next(error)
17 const patternFile = /\.(jpg|jpeg|png|svg|gif|raw|webp)$/gi.test(file.productImage.name)
18
19 if (patternFile) {
20 const pathFile = resolve(process.cwd(), 'servers/uploads/', file.productImage.name)
21 const fileExits = existsSync(pathFile)
22 if (!fileExits) {
23 writeFileSync(pathFile)
24 req.users = JSON.parse(JSON.stringify({ fields, file }))
25 return next()
26 }
27 req.users = JSON.parse(JSON.stringify({ fields, file }))
28 return next()
29 }
30 })
31}
32
1const express = require('express');const formidable = require('formidable'); const app = express(); app.get('/', (req, res) => { res.send(` <h2>With <code>"express"</code> npm package</h2> <form action="/api/upload" enctype="multipart/form-data" method="post"> <div>Text field title: <input type="text" name="title" /></div> <div>File: <input type="file" name="someExpressFiles" multiple="multiple" /></div> <input type="submit" value="Upload" /> </form> `);}); app.post('/api/upload', (req, res, next) => { const form = formidable({ multiples: true }); form.parse(req, (err, fields, files) => { if (err) { next(err); return; } res.json({ fields, files }); });}); app.listen(3000, () => { console.log('Server listening on http://localhost:3000 ...');});