【问题标题】:how to pass file names from multer to another middleware?如何将文件名从 multer 传递到另一个中间件?
【发布时间】:2018-06-21 23:38:21
【问题描述】:

Multer 将我上传的文件放入文件对象中,这样我们就可以通过文件访问它,但是 req.body.image 是空的,我希望能够将 file.originalname 传递给 req.body.image 作为存储磁盘位置的路径。现在,我在这里处理多个文件,所以我想将它们的路径存储在 req 对象中并在另一个中间件中访问它。 我试过这样的东西

req.body.image.push(`path/${file.originalname}`)

返回错误

TypeError: 无法读取未定义的属性“push”

【问题讨论】:

    标签: javascript node.js express multer


    【解决方案1】:

    TypeError: 无法读取未定义的属性“push”

    当您使用push() 时,看起来req.body.image 不是数组而是undefined

    当 multer adds a single file 到请求对象时,它会将它们添加到 req.file 属性中。然后,您可以在后续中间件中访问req.file,如下例所示。如果您有multiple uploaded files,那么您将访问文件数组req.files 并遍历集合以访问每个文件对象。

    在上面的代码中,您正在修改req.body 对象并添加属性image,我不建议更改req.body 对象。最好不要改变请求标头或正文之类的内容。相反,您可以向请求对象添加一个新属性 req.image

    下面的示例使用路由器中间件来封装上传逻辑,(通常应该保留在单个路由中),然后将该中间件添加到 Express Server。

    imageUploadRouter.js

    // imageUploadRouter.js
    const router = require('express').Router()
    const multer = require('multer')
    const upload = multer({dest: 'uploads/'})
    
    router.use(upload.single('image'))
    router.use((req, res, next) => {
      if (!Array.isArray(req.image)) {
        req.image = []
      } 
    
      if (req.file) {
        req.image.push(`path/${req.file.originalName}`)
      }
    
      return next()
    })
    
    // add some additional routes for logic
    router.post('/', (req, res) => {
      // do something and respond
      // you can access req.image here too
      return res.sendStatus(201)
    })
    
    module.exports = router
    

    server.js

    // server.js
    const express = require('express')
    const ImageUploadRouter = require('./imageUploadRouter')
    
    const server = new Express()
    const port = process.env.PORT || 1337
    
    server.use('/images', ImageUploadRouter)
    server.listen(port, () => console.log(`Lisening on ${port}`))
    

    【讨论】:

    • 谢谢,有帮助。
    猜你喜欢
    • 2021-05-21
    • 1970-01-01
    • 2020-07-10
    • 2019-09-08
    • 2014-07-02
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多