简体   繁体   中英

Multer file upload error (nodejs and react)

I've sent this request from client.

if(file){
      const data = new FormData()
      const fileName = Date.now() + file.name
      data.append('file', file) // file comes from state while submitting
      data.append('name', fileName)
      try {
        await axios.post('/upload_image', data)      
      } catch (error) {
        console.log(error.message);
      }
}

Nodejs

const multer = require('multer')


// file upload
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    console.log(req.body);
    cb(null, "./public/images/");
  },
  filename: (req, file, cb) => {
    cb(null, req.body.name)
  },
});
const upload = multer({ storage });
router.post("/upload_image", upload.single('file'), (req,res)=>{
  console.log(req.body);
    try {
        res.status(200).json("file uploaded successfully")
    } catch (error) {
        console.log(error.message);
    }
});

If I print req.body in

router.post("/upload_image", upload.single('file'), (req,res)=>{
 console.log(req.body.name)
console.log(req.file)
......................
.......................
})

Here name gets printed and req.file also gets printed. But, inside

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    ...................
..............................
  },
  filename: (req, file, cb) => {
    console.log(req.body.name); //undefined  
    cb(null, req.body.name)
  },
});

name becomes undefined and app gets crashed. Why the req object didn't go to diskStorage function. What is the issue here?

From multer documentation :

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

If you append the name before the file in the frontend, the name should be available at req.body.name .

// Append name first before we send the file
// so we can access it in the backend
data.append('name', fileName);
data.append('file', file);

Alternatively, you can send the file name directly with the file as the 3rd argument to the append function:

data.append('file', file, fileName);

You can then access the file name in the backend with req.file.originalname . Consult this free Request Parsing in Node.js Guide whenever you're working with file uploads in Node.js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM