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}
321const http = require('http');const formidable = require('formidable'); const server = http.createServer((req, res) => { if (req.url === '/api/upload' && req.method.toLowerCase() === 'post') { // parse a file upload const form = formidable({ multiples: true }); form.parse(req, (err, fields, files) => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ fields, files }, null, 2)); }); return; } // show a file upload form res.writeHead(200, { 'content-type': 'text/html' }); res.end(` <h2>With Node.js <code>"http"</code> module</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="multipleFiles" multiple="multiple" /></div> <input type="submit" value="Upload" /> </form> `);}); server.listen(8080, () => { console.log('Server listening on http://localhost:8080/ ...');});