最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

node.js - Why multer.diskStorage() is not called? - Stack Overflow

matteradmin9PV0评论

Newcomer to nodejs.

I write the code below and use thunder client to test, finding an error: 500.

Image storage engine
const storage = multer.diskStorage({
  destination: './upload/images',
  filename: (req, file, cb)=>{
    return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
  }
})
const upload = multer({storage: storage})
// Create upload endpoint for images
app.use('/images', express.static('upload/images'))
app.post("/upload", upload.single('product'), (req, res)=>{
  res.json({
      success: 1,
      image_url: `http://localhost:${port}/images/${req.file.filename}`
  })
})

This is the error information.

TypeError: Cannot read properties of undefined (reading 'filename')
    at /home/pp/Desktop/E-Commerce/backend/index.js:37:62
    at Layer.handle [as handle_request] (/home/pp/Desktop/E-Commerce/backend/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/pp/Desktop/E-Commerce/backend/node_modules/express/lib/router/route.js:149:13)
    at Immediate._onImmediate (/home/pp/Desktop/E-Commerce/backend/node_modules/multer/lib/make-middleware.js:53:37)
    at process.processImmediate (node:internal/timers:478:21)

If I remove image_url, the test can be passed. I am sure other part of the code is correct, because if I remove the code above, everything goes fine.

But actually I am wondering if multer is actually working, because when I add an output in multer.diskStorage() and execute the code below, there is no "hello" on the console. So I think multer.diskStorage() function is not called at all.

Image storage engine
const storage = multer.diskStorage({
  destination: './upload/images',
  filename: (req, file, cb)=>{
    console.log("hello")
    return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
  }
})
const upload = multer({storage: storage})
// Create upload endpoint for images
app.use('/images', express.static('upload/images'))
app.post("/upload", upload.single('product'), (req, res)=>{
  res.json({
      success: 1,
  })
})

Anyone met such problem before? Thanks a lot!

Post a comment

comment list (0)

  1. No comments so far