Home > database >  multer save file, nidejs angular
multer save file, nidejs angular

Time:05-09

i want to save an image on nodejs, i am sending the file via post, whith angular like this:

...
flag: File;

flaginput(event){
 this.flag = event.target.files[0];
}

submit(){
 this.http.post('localhost...', this.flag).subscribe( x => {
  console.log(x.response)});

and in nodejs

const multer = require('multer');

const storage = multer.diskStorage({
destination: function(req,file,cb){
    cb(null, './imagenes/');
},
filename: function(req,file,cb){
    cb(null, file.originalname)
}
});

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

module.exports = (app) =>{

app.post("/equipos", upload.single(), (req, res, next) => {
    console.log(req.file)

    base.query('SELECT * FROM names', (error, result) =>{
        if(error){
            res.json({mensaje: "error", datos: error});
        }else{
            res.json({mensaje: "equipo creado"});
        }
    })
})

but im not sure of how to save the file or why its is not saving, on console it dosnt appear to be any error, on nodejs when i try console.log(req.file) is undefined

i want to save the file on the folder ./imagenes.

i also try to send it as a json {flag: this.flag}, and also try to send it in a formData changing the upload.single() to upload.single('flag') but isn working

thanks for the help

CodePudding user response:

Multer works with formData.

Your multer diskStorage config seems ok, but you should use formData.


Client side request

upload(img: File) {
  const formData: FormData = new FormData();
  formData.append("img", img);
  return this.httpClient.post('http://localhost:3000/equipos', formData);
}

Server side

app.post('/equipos', upload.single('img'), async (req, res) => {
    return res.status(200)
        .json('Image saved')
})
  • Related