Advertisement
aldikhan13

BEST PRACTICE USING FORMIDABLE - MIDDLEWARE

Nov 23rd, 2020 (edited)
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { IncomingForm } = require('formidable')
  2. const { resolve } = require('path')
  3. const { existsSync, writeFileSync } = require('fs')
  4.  
  5. module.exports = (req, res, next) => {
  6.   const form = new IncomingForm({
  7.     maxFileSize: 1 * 1024 * 1024,
  8.     keepExtensions: true
  9.   })
  10.  
  11.   form.parse(req, (error, fields, file) => {
  12.     if (error) return next(error)
  13.  
  14.     const patternFile = /\.(jpg|jpeg|png|svg|gif|raw|webp)$/gi.test(file.productImage.name)
  15.  
  16.     if (patternFile) {
  17.       const pathFile = resolve(process.cwd(), 'servers/uploads/', file.productImage.name)
  18.       const fileExits = existsSync(pathFile)
  19.  
  20.       if (!fileExits) {
  21.         writeFileSync(pathFile)
  22.         req.users = JSON.parse(JSON.stringify({ fields, file }))
  23.         return next()
  24.       }
  25.  
  26.       req.users = JSON.parse(JSON.stringify({ fields, file }))
  27.       return next()
  28.     }
  29.   })
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement