In your express app install package express-fileupload
in app.js
const fileUpload = require("express-fileupload");
also add
app.use(fileUpload({
createParentPath: true,
useTempFiles: true,
tempFileDir: '/tmp/',
limits: {
fileSize: 1024 * 1024 * 1
},
abortOnLimit: true
}));
in users route add
var express = require('express');
var router = express.Router();
var path = require('path')
var moment = require('moment')
router.post('/fileupload', function (req, res, next) {
const profilePic = req.files.profilePic;
const extensionName = path.extname(profilePic.name); // fetch the file extension
const allowedExtension = ['.png', '.jpg', '.jpeg'];
if (!req.files) {
return res.status(400).send("No files were uploaded.");
}
if (!allowedExtension.includes(extensionName)) {
return res.status(422).send("Invalid Image");
}
var currentDate = new moment()
var dateString = currentDate.format('DDMMYYHHmmss')
var uploadPath = require('path').resolve('./')
uploadPath = uploadPath + '/public/uploads/profilePic/' + dateString + '_' + profilePic.name;
profilePic.mv(uploadPath, (err) => {
if (err) {
return res.status(500).send(err);
}
return res.send({ status: "success", body: req.body });
});
});
The posted form data will be in req.body while file in req.files
you are good to go,the entire code is at
https://github.com/gitsangramdesai/express-fileupload-no-multer
No comments:
Post a Comment