how can I use the submiting data related to image pass to server using multer before uploading it to disk .Is it possible ? if not then please give me another solution.
I want to check the size of file its should be at least 4mp resolution ,if its has lesser then that the images should not be uploaded and send the error msg
exports.uploadimg=(req,res,next)=>{
uploadphoto(req, res, (err) => {
if (err) {
res.render("upload")
}
else {
res.send("photo uloaded")
}
})
I take it you have some multipart middleware (say connect-multiparty) reading request payload for multipart/form-data
requests.
This middleware would have provided you with a files
object on the request
object (request.files
). The properties of the files
object are keys for each file upload field. The value for each of such property can be an object (a single file upload) or an array (multiple files upload). Each of these objects nested within the files
object have properties describing the actual file uploaded and allows you to run checks as you see fit in a following middleware.
// router declarations
const {Router} = require('express');
const multipart = require('connect-multipart');
const multipartMiddleware = multipart();
const validateFileSize = (file) => {
/*
Each file has the following property:
fieldName - same as name - the field name for this file
originalFilename - the filename that the user reports for the file
path - the absolute path of the uploaded file on disk
headers - the HTTP headers that were sent along with this file
size - size of the file in bytes
*/
// check against file size
if (file.size < 4 * 1024 * 1024) throw new Error('File is too small');
}
const validateImageMiddleware = (req, res, next) => {
// say we expected an upload field with key "productImage"
const { files: { productImage } } = req;
const isMultiple = Array.isArray(productImage);
if (isMultiple) {
productImage.forEach(validateFileSize);
} else {
validateFileSize(productImage);
}
// if we got here, the files were valid so we go to next handler
next();
};
const myRouter = Router();
myRouter.post('/expect-file', multipartMiddleware, validateImageMiddleware, (req, res) => {
// do whatever you want to do
res.send('Success');
});