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

使用multer配置storage无法上传文件问题求助

Multer配置diskStorage后文件未保存、路由回调不执行的问题解决
  • 路由拼写错误导致回调不执行
    你的代码里把Router误写为Rounter,这会导致该POST路由无法被正确注册,所以后续的console.log('test')完全不会触发。修正拼写为Router.post(...)即可解决回调不执行的问题。

  • 目标目录未自动创建
    使用diskStorage模式时,Multer不会自动创建destination指定的目录(但dest模式下会自动创建目录)。你需要手动确保目标目录存在,或者在destination回调里通过文件系统模块创建目录:

    const fs = require('fs');
    const path = require('path');
    
    const storage = multer.diskStorage({
        destination: (req, file, callback) => {
            const uploadDir = path.join(__dirname, 'uploads/');
            // 检查目录是否存在,不存在则递归创建
            if (!fs.existsSync(uploadDir)) {
                fs.mkdirSync(uploadDir, { recursive: true });
            }
            callback(null, uploadDir);
        },
        filename: (req, file, callback) => {
            const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
            // 保留原文件后缀
            const ext = path.extname(file.originalname);
            callback(null, file.fieldname + '-' + uniqueSuffix + ext);
        }
    });
    const upload = multer({ storage: storage });
    // 修正路由拼写
    Router.post('/create-user-admin', upload.single('avatar'), (req, res) => {
        console.log('test');
        // 记得返回响应,避免请求挂起
        res.status(200).json({ msg: '文件上传成功' });
    });
    
  • 补充:保留文件后缀
    如果你需要保留原文件的后缀名,可以通过path.extname(file.originalname)获取后缀并拼接到最终文件名中,上述代码已包含该处理逻辑。

内容的提问来源于stack exchange,提问作者Phan Vĩnh Khang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:04:53