Answers for "formidable express"

2

formidable express

// 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()
    }
  })
}
Posted by: Guest on November-24-2020
0

express formidable

const 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 ...');});
Posted by: Guest on August-18-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language