You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取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 upload callback runs only after all file processing completes. A null err guarantees 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 .PNG or .JPG that would otherwise be rejected.

内容的提问来源于stack exchange,提问作者Mrugesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:48:46