Validations before upload
Hello guys,
I'm trying to submit a multipart form data to a nodejs server, and I'd like to check if all required fields exist in the form, before the upload starts.
However, multer only finish the form parsing after the upload is complete.
Anyone know how I can check the form fields before the upload? I'm not interested in uploading files first, and only then check if the other form data is valid.
Thanks guys!
This might actually be quite a challenge since the browser is free to (and often does, see below) send files and fields mixed and in any order. This means that multer can't read the fields first, and then decide if it should continue with the files or bail on the stream.
However, there is a "workaround" if you really need it. If you construct a FormData object with javascript on the client, you could potentially let the browser know in which order you want it to send things. Now, as fair as I know, the spec dosen't say that the browser should send things in the same order that you .append() them, but it seems to be working for now.
The second part now is to somehow instruct multer to discontinue if there is a problem with the fields. I'm pretty sure that it's currently possible with all the hooks that we expose. But we are working on minimizing that in #131. I don't think it's that interesting if it's possible or not, but wether there is a clear path of expressing this intent or not.
With the new code, I actually think that there is. You could use the fileFilter feature to express that "only accept files if valid fields has preceded it". Something like this:
let multer = require('multer')
function hasRequiredFields (fields) {
// 1. Implement this!
}
let upload = multer({
fileFilter: function (req, file, cb) {
cb(null, hasRequiredFields(req.body))
}
})
app.post('/upload', upload, function (req, res) {
// 2. Handle the request
})
// 3. ????
// 4. PROFIT!!
Multer 1.0.0 is now released and you should be able to use the workaround suggested above.
Unfortunately there is nothing we can do about the order in which the browsers send things.
Hi @LinusU , As you said above.
app.post('/upload', upload, function (req, res) {
// 2. Handle the request
})
the "upload" looks like a router middleware, and the router middleware required to be a function. But the "update" is an object In fact.
the source code as follow.
function multer (options) {
if (options === undefined) {
return new Multer({})
}
if (typeof options === 'object' && options !== null) {
return new Multer(options)
}
throw new TypeError('Expected object for argument options')
}
SO, I got an error.
Error: Route.post() requires callback functions but got a [object Object]
Yeah I posted the workaround before 1.0 was released so it didn't account for that syntax.
You need to change it into one of the new functions for accepting files, e.g. upload.single('avatar'). Which one you should choose depends on what files you want to accept, check the documentation for more information.
Is there any work around besides the one above ? @LinusU I want to use my Joi middleware but if the multer middleware comes before it then req.body is undefined meaning that its not being parsed.
For example:
router.post('/savings/', idValidaiton.validateIdKey, validCompany,parser.single('imageUrl'),
createSavings )
The above wont work but the below works:
router.post('/savings/', parser.single('imageUrl'),idValidaiton.validateIdKey, validCompany,
createSavings )
So basically the image is uploaded before the req.body is validate
My parse Middleware looks like this:
const multer = require('multer')
const cloudinary = require('cloudinary')
const cloudinaryStorage = require('multer-storage-cloudinary')
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.CLOUD_API_KEY,
api_secret: process.env.CLOUD_API_SECRET
})
const storage = cloudinaryStorage({
cloudinary: cloudinary,
folder: 'ratehogs',
allowedFormats: ['jpg', 'png', 'jpeg'],
transformation: [{ width: 500, height: 500, crop: 'limit' }]
})
const parser = multer({ storage: storage })
module.exports = parser
Trying to see how i can incorporate you solution
This might actually be quite a challenge since the browser is free to (and often does, see below) send files and fields mixed and in any order. This means that multer can't read the fields first, and then decide if it should continue with the files or bail on the stream.
However, there is a "workaround" if you really need it. If you construct a
FormDataobject with javascript on the client, you could potentially let the browser know in which order you want it to send things. Now, as fair as I know, the spec dosen't say that the browser should send things in the same order that you.append()them, but it seems to be working for now.The second part now is to somehow instruct multer to discontinue if there is a problem with the fields. I'm pretty sure that it's currently possible with all the hooks that we expose. But we are working on minimizing that in #131. I don't think it's that interesting if it's possible or not, but wether there is a clear path of expressing this intent or not.
With the new code, I actually think that there is. You could use the
fileFilterfeature to express that "only accept files if valid fields has preceded it". Something like this:let multer = require('multer') function hasRequiredFields (fields) { // 1. Implement this! } let upload = multer({ fileFilter: function (req, file, cb) { cb(null, hasRequiredFields(req.body)) } }) app.post('/upload', upload, function (req, res) { // 2. Handle the request }) // 3. ???? // 4. PROFIT!!
What if I don't attach file at all? Then this fileFilter won't be fired meaning req without file will be forwarded next
Will test it out and advise
Will test it out and advise
u were able to make that work?
suggestion: what about sending a request to validate only text fields first and if validation passes, then you send another request with the validated data and the file you want to upload
Is there any work around besides the one above ? @LinusU I want to use my Joi middleware but if the multer middleware comes before it then req.body is undefined meaning that its not being parsed.
For example:
router.post('/savings/', idValidaiton.validateIdKey, validCompany,parser.single('imageUrl'), createSavings )The above wont work but the below works:
router.post('/savings/', parser.single('imageUrl'),idValidaiton.validateIdKey, validCompany, createSavings )So basically the image is uploaded before the req.body is validate
My parse Middleware looks like this:
const multer = require('multer') const cloudinary = require('cloudinary') const cloudinaryStorage = require('multer-storage-cloudinary') cloudinary.config({ cloud_name: process.env.CLOUD_NAME, api_key: process.env.CLOUD_API_KEY, api_secret: process.env.CLOUD_API_SECRET }) const storage = cloudinaryStorage({ cloudinary: cloudinary, folder: 'ratehogs', allowedFormats: ['jpg', 'png', 'jpeg'], transformation: [{ width: 500, height: 500, crop: 'limit' }] }) const parser = multer({ storage: storage }) module.exports = parserTrying to see how i can incorporate you solution
I am facing the exact same issue @Enado95 did you found a workaround to overcome this issue? Does anyone have a workaround how can I validate the request body before the upload start?
What if I don't attach file at all? Then this fileFilter won't be fired meaning req without file will be forwarded next
@tar-aldev If you don't attach files, req.file will be undefined and you can handle this in your middleware after the upload function with something like:
app.post('/upload', upload, function (req, res) {
const image = req.file;
if (!image) {
// Handle no image here...
}
})
Hello guys,
I'm trying to submit a multipart form data to a nodejs server, and I'd like to check if all required fields exist in the form, before the upload starts.
However, multer only finish the form parsing after the upload is complete.
Anyone know how I can check the form fields before the upload? I'm not interested in uploading files first, and only then check if the other form data is valid.
Thanks guys!
- multer to read the form data and access files in req.files
- fs to move the images from req.files to the desired folder
Use any() in the routes firstly to get the images in req.files
const multer = require('multer') const formData = multer() router.post('/signup', formData.any(), signUpValidation, signUpcall)
req.files will contain an array of objects. Each object contains a file or image in a buffer format. After validation , in the final function use the 'fs' module to move the image to your destined folder.
const fs = require("fs"); const buffer = req.files[0].buffer fs.writeFileSync('./storage/coverPic/' + req.files[0].originalname, buffer)
this works
Further more on @kalyanrajKrify comment
You can create a middleware
function saveFile(pathToSave: string) {
return (req: Request, res: Response, next: NextFunction) => {
const rootPath = path.resolve(__dirname, "..");
const folderPath = path.join(rootPath, pathToSave);
try {
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
}
if (!req.files || !req.files.length) return next();
const filesLen = req.files.length as number;
for (let i = 0; i < filesLen; i++) {
req.files[i].fileName =
generateRandomString() + "_" + req.files[i].originalname;
fs.writeFileSync(
pathToSave + req.files[i].fileName,
req.files[i].buffer
);
}
next();
} catch (error) {
next(error);
}
};
}
Append to
router.post('/signup', formData.any(), signUpValidation, saveFile(pathToFile), signUpcall)
Note: This handles multi files, creates the folder if it doesnt exist and saves each one
The same problem I am facing from a long time but not getting a good solution.
But by investing my lot of time, I finally find an awesome solution. But before sharing this solution I just want to explain the problem again.
The problem arises when dealing with a form that includes both input fields and file upload field. The desired approach is to validate all the form fields before proceeding with the file upload.
If you were to upload the files on server directory before validating the fields, and the server detects any validation errors during the processing of the form data, it would need to return an error response to the client. In such a scenario, the client would have to resubmit the form, including the files, causing unnecessary and potentially large file uploads.
If the client has to repeatedly submit the form with files due to validation errors, it would result in increased server upload size. Each resubmission would include the files, even though the validation errors might be unrelated to the file content. This additional file upload can consume server resources and impact performance, especially when dealing with large files.
By deferring the file upload until after field validation, this issue can be avoided.
So the proposed solution is that:
const registerUser = async (req, res, next) => {
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads');
},
filename: function (req, file, cb) {
const fileName = file.originalname.split('.')[0];
const fileExtension = file.originalname.split('.')[1];
cb(null, `${fileName}-${Date.now()}.${fileExtension}`);
}
});
async function fileFilter(req, file, cb) {
// Validate request body with Joi schema
const { error, value } = validate(req.body);
if (error) {
cb(
new AppError(
"Validation Errors",
422,
error.details.map(elem => ({ [elem.context.key]: elem.message }))
),
false
);
}
// Check if username already exists in database
let checkUsername = await User.findOne({ username: value.username });
if (checkUsername) cb(new AppError("Username is already taken!", 400), false);
// Check if user email already exists in database
let checkEmail = await User.findOne({ email: value.email });
if (checkEmail) cb(new AppError("User email is already Registered!", 400), false);
if (!file) {
cb(new AppError("Avatar Image is Required!", 400), false);
}
// Check if the file is an image with the allowed extensions
const fileExtension = path.extname(file.originalname).toLowerCase();
const allowedExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp'];
const isImage = file.mimetype.startsWith('image/');
const isAllowedExtension = allowedExtensions.includes(fileExtension);
if (!isImage || !isAllowedExtension) {
cb(new AppError('Invalid file type. Only image files (PNG, JPG, JPEG, GIF, and WebP) are allowed.', 400), false);
}
cb(null, true);
};
const limits = {
fileSize: 1 * 1000 * 1000, // 1 MB
files: 1,
};
const upload = multer({ storage, limits, fileFilter }).single('avatar');
upload(req, res, async (err) => {
try {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
throw new AppError(`File ${err.field} upload exceeds the maximum file size limit!`, 400);
}
}
else if (err instanceof AppError) {
throw err;
}
// Create new user in database
let user = new User({
username: req.body.username,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password,
avatar: req.file.path
});
// Hash password and save user to database
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
await user.save();
return res.status(200).json(success("User created successfully", 200));
}
catch (err) {
return next(err);
}
});
};