Search code examples
javascriptmulter

cant save a file after uploading multer


<form action="/upload" method="post">
<input type="file" name="avatar" id="avatarinput" onchange="readfichier()"> 
<button type='submit'>Save</button>
</form>

SERVER

app.post('/upload', upload.single('avatar'), function (req, res, next) {
    console.log(req.file);

    fs.rename(req.file.path, 'uploads/'+req.file.originalname, function (err) {
         if (err) throw err;
          console.log('renamed complete');
    });

    res.end('Success');
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

I got this error: TypeError: Cannot read properties of undefined (reading 'path')


Solution

  • First, you need to use a disk storage engine to take full control on storing files to disk.

    const storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './uploads')
      },
      filename: function (req, file, cb) {
        cb(null,file.fieldname+'-'+Date.now()+'.'+file.mimetype.split('/').reverse()[0]);
      }
    })
    
    const upload = multer({ storage: storage })
    

    Now, define your route and add multer as a middleware.

    app.post('/upload', upload.single('avatar'), function (req, res, next) {
        console.log(req.file);
    
        fs.rename(req.file.path, 'uploads/'+req.file.originalname, function (err) {
             if (err) throw err;
              console.log('renamed complete');
        });
    
        res.end('Success');
    })
    

    This much is described very well in previous answers as well. But the thing you're missing is to add enctype="multipart/form-data" into your HTML form. Read more about why we need to do this here.

    <form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="avatar" id="avatarinput" onchange="readfichier()"> 
    <button type='submit'>Save</button>
    </form>
    

    I hope this solves all your issues. If not, refer to this answer.