如何获取Multer文件完全上传至磁盘后的回调?
How to detect when Multer has successfully written files to disk?
Your Current Code
const storage = multer.diskStorage({ destination(req, file, callback) { callback(null, './public/images') }, filename(req, file, callback) { profile_image = `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`; callback(null, profile_image) } }); const xyz = (req, res) => { upload = multer({ limits: { fileSize: 1000000, files: 2 }, storage, fileFilter(req, file, callback) { const ext = path.extname(file.originalname); if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') { return callback(res.end('Only images are allowed'), null) } callback(null, true); } }).any(); upload(req, res, err => { }) }
The Answer
Great question! Let's break down how to confirm when files are safely written to disk with Multer:
First off, the callback you're already passing to upload(req, res, err => {}) is exactly the right spot to detect successful file writes. Multer only triggers this callback after it's finished processing all files—including writing them to your specified destination folder. If the err parameter is null, that means every file was uploaded and saved to disk without issues.
Here's how to update your code to use this callback effectively, plus a few tweaks to clean up your existing logic:
const storage = multer.diskStorage({ destination(req, file, callback) { callback(null, './public/images') }, filename(req, file, callback) { // Use a local variable instead of global to avoid scope pollution const profile_image = `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`; callback(null, profile_image) } }); const xyz = (req, res) => { // Define upload as a local variable (or move this outside the handler for reusability) const upload = multer({ limits: { fileSize: 1000000, files: 2 }, storage, fileFilter(req, file, callback) { const ext = path.extname(file.originalname).toLowerCase(); // Handle case sensitivity const allowedExts = ['.png', '.jpg', '.gif', '.jpeg']; if (!allowedExts.includes(ext)) { // Pass an Error object to the callback instead of ending the response directly return callback(new Error('Only image files (PNG, JPG, GIF, JPEG) are allowed'), false); } callback(null, true); } }).any(); upload(req, res, (err) => { if (err) { // Handle all upload errors consistently here return res.status(400).send(err.message); } // If we reach this point, ALL files have been successfully written to disk! console.log('Files uploaded and saved to disk successfully'); console.log('Uploaded files details:', req.files); // Access file metadata here // Send a success response to the client res.status(200).send('Files uploaded successfully'); }); }
Key Notes:
- Success Confirmation: The
uploadcallback runs only after all file processing completes. Anullerrguarantees files are safely stored on disk. - Clean Error Handling: Instead of ending the response directly in
fileFilter, pass an Error object to the callback. This lets you handle all upload errors (invalid types, size limits, etc.) in one place. - Scope Best Practices: Avoid global variables like
profile_image—local variables prevent unexpected behavior in concurrent requests. - Case Insensitivity: Converting the file extension to lowercase ensures you catch cases like
.PNGor.JPGthat would otherwise be rejected.
内容的提问来源于stack exchange,提问作者Mrugesh
相关产品推荐
相关产品推荐

