1
<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')

2 Answers2

1

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.

Amit
  • 1,018
  • 1
  • 8
  • 23
0

I guess this is the only code you have.

first you have to define multer as middleware of an your api

then you have to told your multer that where you want to store your image
I guess it's in your disk

so on your server code looks like this

var multer = require('multer');  
var 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]);
    },
});

var upload = multer({storage: storage}); 



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
})
Piyush Jain
  • 313
  • 3
  • 10