expressjs / expressjs/multer

Prevent File Upload when error occurs in the validation

Open
#1,153 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
12.1k
Forks
1.1k
Avg merge
8d 2h
Merged PRs (30d)
21

Description

Is there a way to stop file upload in multer when validation fails during saving into a MongoDB database?
My code goes like this.
```
const EmployeeSchema = new mongoose.Schema(
{
EmployeeId: {
type: String,
required: true,
unique: true,
}
firstName: String,
lastName: String,
imagePic: String,

}

const PUBLIC_DIR = "./public/";

// set multer disk storage
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, PUBLIC_DIR );
},
filename: (req, file, cb) => {
//generate random uuid
const fileName = uuidv4() + path.extname(file.originalname);
cb(null, fileName);
},
});

const upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (
file.mimetype == "image/png" ||
file.mimetype == "image/jpg" ||
file.mimetype == "image/jpeg"
) {
cb(null, true);
} else {
cb(null, false);
return cb(new Error("Only .png, .jpg and .jpeg format is allowed!"));
}
},
});

// Create Employee
router.post("/", upload.single("file"), async (req, res) => {
const newEmployee = new Employee(req.body);
try {
// save the generated filename in our MongoDB Atlas database
newEmployee.imagePic = req.file.path;

const savedEmployee = await newEmployee.save();
res.status(200).json(savedEmployee);
} catch (error) {
res.status(500).json({ error: error });
}
});
```
I noticed that if validation or an error is thrown during the save() then the file is still uploaded in my upload directory.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.