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

为什么设置multer diskStorage的destination后仍无法保存上传文件到指定目录?

问题原因与解决方案

你遇到的上传文件未写入本地的问题由两处配置错误导致:

  • multer.diskStorage 中 destination 的回调函数调用不符合规范
  • multer 实例化时配置项键名拼写错误
  • 额外注意:multer 默认不会自动创建不存在的存储目录,需要提前在项目根目录下创建 upload 文件夹

错误1:destination回调调用错误

diskStorage 中 destination 的回调函数cb的传参规则为:第一个参数是错误对象,无错误时传null,第二个参数是文件存储路径。你的代码中将错误处理函数作为第一个参数传入,相当于告知multer出现异常,中断了存储逻辑。

错误2:multer配置项键名错误

multer 接收的配置对象中,自定义存储的配置键是小写的storage,你代码中写的是大写开头的Storage,导致自定义的磁盘存储配置未生效,multer 默认使用内存存储,不会写入本地磁盘。


修正后的 multer 配置代码

const multer = require('multer')
const fs = require('fs')
const path = require('path')

// 自动创建upload目录,避免手动创建遗漏
const uploadDir = path.join(__dirname, 'upload')
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true })
}

const storage = multer.diskStorage({
    destination: function(req,file,cb){
        // 无错误时第一个参数传null
        cb(null, uploadDir)
    },
    filename: function(req,file,cb){
        const ext = file.originalname.substr(file.originalname.lastIndexOf('.'))
        cb(null,file.fieldname + '-' + Date.now()+ ext)
    }
})

// 配置项键名改为小写storage
module.exports = store = multer({ storage })

修改后重启服务即可正常将上传的文件写入upload目录。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:06:04