Express multer

PHOTO EMBED

Wed Oct 06 2021 02:35:12 GMT+0000 (UTC)

Saved by @ExplodeMilk #typescript

import multer from 'multer';

// see customize section
const upload = multer({dest:'uploads/'})

const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.post('/contact',upload.single('profile'),(req,res)=>{
    console.log(req.file.key); // get the name of the file
    console.log(req.body); // Other fields are in req.body
    res.redirect('/');
})

// ----------------------------------
// upload options
upload.single("field-name");
upload.array("field-name");
upload.fields([
  { name: 'avatar', maxCount: 1 },
  { name: 'gallery', maxCount: 8 }
])

// ---------------------------------
// customize multer
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, path.resolve('/uploads'));
    },
    filename: function (req, file, cb) {
      cb(null, `${file.fieldname}-${Date.now()}.${file.mimetype.split('/')[1]}`);
    }
  })
const upload = multer({storage})
content_copyCOPY

npm install multer @types/multer