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

如何添加Multer实现文件上传?数据库记录已保存但文件未上传无报错

Fix: File Not Uploading Even Though Database Record Saves

Hey there, I spot the issue immediately—you're ending the HTTP response before your file upload and database logic is fully wrapped up. Let's break this down and fix it step by step:

What's Going Wrong

You call res.end("File is uploaded") right after multer finishes handling the file upload, but this terminates the response stream immediately. Even though the database save still runs in the background, the frontend gets a response before all operations are complete, and you can't properly confirm that both the file upload and database save succeeded. Worse, if something fails with the database save after you've already ended the response, you can't send an error back to the client.

Fixed Code

var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});
var upload = multer({ storage : storage}).single('document');
export function store(req, res) {
  upload(req,res,function(err) {
    if(err) {
      // Send error immediately if upload fails
      return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: err })
    }
    
    // Handle database save only after upload is confirmed successful
    const {leave_type, comments, date_from, date_to, blocked_dates} = req.body;
    leaves.forge({
      leave_type, comments, date_from, date_to, blocked_dates
    }).save()
    .then(leaves => {
      // Send a single unified response once all operations are done
      res.json({ 
        success: true, 
        message: "File uploaded and record saved successfully",
        data: leaves.toJSON() 
      })
    })
    .catch(err => {
      // Send error if database save fails
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: err })
    });
  });
}

Key Modifications

  • Removed the premature res.end() call: Now we only send a response after both the file upload and database save are completed successfully.
  • Combined success feedback: The client gets a single clear response confirming both operations worked, which simplifies frontend handling.
  • Proper error flow: If either the upload or database save fails, we send the appropriate error status and message back to the client.

Quick Verification Checks

  1. Ensure the ./uploads directory exists! Multer will throw an error if it can't find the destination folder. If it doesn't exist, add code to create it automatically:
const fs = require('fs');
const path = require('path');

var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    const uploadPath = path.join(__dirname, './uploads');
    // Create directory (and parent folders if needed) if it doesn't exist
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }
    callback(null, uploadPath);
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});
  1. Double-check that your frontend sends the request with the multipart/form-data content type—this is mandatory for multer to parse the file correctly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:16:42