formidable nodejs example

JavaScript
// make this a middleware function, 
// then put it on the route like you used jwt,
// then get the value with req.users.

const { IncomingForm } = require('formidable')
const { resolve } = require('path')
const { existsSync, writeFileSync } = require('fs')

module.exports = (req, res, next) => {
  const form = new IncomingForm({
    maxFileSize: 1 * 1024 * 1024,
    keepExtensions: true
  })

  form.parse(req, (error, fields, file) => {
    if (error) return next(error)
    const patternFile = /\.(jpg|jpeg|png|svg|gif|raw|webp)$/gi.test(file.productImage.name)

    if (patternFile) {
      const pathFile = resolve(process.cwd(), 'servers/uploads/', file.productImage.name)
      const fileExits = existsSync(pathFile)
      if (!fileExits) {
        writeFileSync(pathFile)
        req.users = JSON.parse(JSON.stringify({ fields, file }))
        return next()
      }
      req.users = JSON.parse(JSON.stringify({ fields, file }))
      return next()
    }
  })
}
const 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/ ...');});
Source

Also in JavaScript: