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

Node.js使用multer+axios上传文件时如何设置自定义文件名

解决方案

第一步:修改前端代码,将id添加到FormData中

你需要把前端定义的id作为普通表单字段追加到用于上传的formData对象内,修改后代码示例如下:

const id = *some value*
// 追加id字段到formData,字段名要和后端取值逻辑对应
formData.append('customId', id)
Axios.post("http://localhost:3001/upload", formData, {headers: {'content-type': 'multipart/form-data'}})
        .then((response) => {
            window.location.reload()
        })

第二步:修改后端multer配置,从请求中取id作为文件名

multer的diskStorage配置的filename回调中,req对象已经完成了formData内普通表单字段的解析,你可以直接从req.body中获取前端传递的id,修改后代码如下:

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, '../client/src/Images')
    },
    filename: (req, file, cb) => {
        // 从req.body中取前端传的customId,加兜底逻辑避免id为空
        const fileName = req.body.customId || Math.trunc(Date.now()/1000).toString()
        cb(null, fileName + path.extname(file.originalname))
    }
})

const upload = multer({
    storage: storage,
    limits:{fieldSize: 1000000},
 })

app.post("/upload", upload.single('image'), (req, res) => {
    res.send("Image Uploaded")
})

注意事项

  • 确保前端追加customId字段的字段名和后端req.body的取值字段完全一致
  • 如果业务允许id重复,建议在文件名后额外加随机后缀或时间戳,避免同名文件覆盖
  • 可添加参数校验逻辑,若req.body.customId为空直接返回参数错误提示,避免生成兜底的时间戳文件名不符合业务预期

内容的提问来源于stack exchange,提问作者Víctor Donat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:15:03