title: file upload using multer middleware with angular 7 mean stack not working
body: <p>Please, I am using multer middleware for file upload in angular mean stack. I can't get req.file but can get req.body meaning the file is not being upload. 
  At first when I upload I check the designated upload folder and I can't see anything but other text data can enter the mongoose database.</p>
  
  <p>I then tried to res.send(req.file.filename) it says could not find property 'filename' of undefined. When I res.send(req.file) it returns null. but when I res.send(req.body) it returns the textual data keyed in from the html form. What have I done wrong?</p>
  
  <p>I have gone through many suggestions to similar problem here on stackoverflow and other places online but none solved the problem for me.</p>
  
  <p>Pls help</p>
  
  <p>Find my code in vehicle.route.js below:</p>
  
  <pre><code>  path = require('path'),
    multer = require('multer'),
  
    app = express();
  
    const DIR = '../uploads/';
    const storage = multer.diskStorage({
      destination: (req, file, cb) =&gt; {
        cb(null, DIR);
      },
      filename: (req, file, cb) =&gt; {
        const fileName = file.fieldname + '-' + Date.now();
        cb(null, fileName)
      }
    });
  
    let upload = multer({ 
      storage: storage
    })
  
  vehicleRouter = express.Router();
  
  // Vehicle model
  let Vehicle = require('../models/Vehicle');
  
  app.use(express.static(path.join(__dirname, '../uploads')));
  
  
  // Get All Employees
  vehicleRouter.route('/').get((req, res, next) =&gt; {
    Vehicle.find((error, data) =&gt; {
      if (error) {
        return next(error)
      } else {
        res.json(data)
      }
    })
  })
  
  
  
  vehicleRouter.post('/register', upload.single('purchaseReceipt'), (req, res, next) =&gt; {
    res.json(req.file.filename)
    return;
  
  /*vehicleRouter.post('/register', upload.single('purchaseReceipt'), (req, res, next) =&gt; {
    res.json(req.file)
    return;
    const vehicle = new Vehicle({
      fullName: req.body.fullName,
      purchaseReceipt: req.file.filename
    });
    vehicle.save().then(result =&gt; {
      console.log(result);
      res.status(201).json({
        message: "Vehicle registered successfully!",
        userCreated: {
          _id: result._id,
          name: result.name,
          purchaseReceipt: result.purchaseReceipt
        }
      })
    })
  
    /*Vehicle.create(req.body, (error, data) =&gt; {
      if (error) {
        return next(error)
      } else {
        res.json(data)
      }
    })*/
  
    //res.json('from register vehicle')
    })
  
    app.use(express.static(path.join(__dirname, './uploads')));
  module.exports = vehicleRouter;```
  
  I tried uploading straight but it isnt then I commented part of the code and tried to send back req.file.filename as response but it is saying: error: "Cannot read property 'filename' of undefined"
  
  [the error code on console][1]
  
  
    [1]: https://i.stack.imgur.com/LY9ob.png
  
  
  vehicle-registration.component.html code ie the html form
  ```&lt;div class="card"&gt;
    &lt;div class="card-body"&gt;
      &lt;form method="post" [formGroup]="vehicleForm" (ngSubmit)="onSubmit()" enctype="multipart/form-data"&gt;
        &lt;div class="form-group"&gt;
          &lt;label class="col-md-4"&gt;Full Name&lt;/label&gt;
          &lt;input type="text" class="form-control" formControlName="fullName" /&gt;
        &lt;/div&gt;
  
        &lt;div class="form-group"&gt;
          &lt;div class="preview" *ngIf="preview &amp;&amp; preview !== null"&gt;
            &lt;img [src]="preview" [alt]="vehicleForm.value.name"&gt;
          &lt;/div&gt;
        &lt;/div&gt;
  
        &lt;!--&lt;div class="form-group"&gt;
          &lt;label class="col-md-4"&gt;Upload Purchase Receipt&lt;/label&gt;
          &lt;input type="text" class="form-control" formControlName="purchaseReceipt" /&gt;
        &lt;/div&gt;--&gt;
        &lt;div class="form-group"&gt;
          &lt;label class="col-md-4"&gt;Upload Purchase Receipt &lt;/label&gt;
          &lt;input type="file" class="form-control"  (change)="uploadFile($event)" formControlName="purchaseReceipt" name="purchaseReceipt"/&gt;
        &lt;/div&gt;
  
        &lt;div class="form-group"&gt;
          &lt;div class="row"&gt;
            &lt;div class="col-sm-3"&gt;
                &lt;button class="btn btn-success btn-sm btn-block" type="submit"&gt;Register Vehicle&lt;/button&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;/div&gt;
  
      &lt;/form&gt;
    &lt;/div&gt;
  &lt;/div&gt;```
  
  
  vehicle-registration.component.ts code
  </code></pre>
  
  <p>import { Component, OnInit } from '@angular/core';
  import { FormGroup, FormBuilder, Validators } from '@angular/forms';
  import { VehicleService } from '../../service/vehicle.service';</p>
  
  <p>@Component({
    selector: 'app-vehicle-registration',
    templateUrl: './vehicle-registration.component.html',
    styleUrls: ['./vehicle-registration.component.css']
  })
  export class VehicleRegistrationComponent implements OnInit {
    preview: string;
    vehicleForm: FormGroup;</p>
  
  <p>constructor(public fb: FormBuilder, private vs: VehicleService) { 
      this.createForm()
    }</p>
  
  <p>ngOnInit() {
    }</p>
  
  <p>createForm() {
      this.vehicleForm = this.fb.group({
       fullName: ['', [Validators.required]],
       purchaseReceipt: [null, [Validators.required]],
      });
    }</p>
  
  <p>uploadFile(event) {
      const file = (event.target as HTMLInputElement).files[0];
      this.vehicleForm.patchValue({
        avatar: file
      });
      this.vehicleForm.get('avatar')
      // .updateValueAndValidity()</p>
  
  <pre><code>// File Preview
  const reader = new FileReader();
  reader.onload = () =&gt; {
    this.preview = reader.result as string;
  }
  reader.readAsDataURL(file)
  </code></pre>
  
  <p>}</p>
  
  <p>onSubmit() {
      if (!this.vehicleForm.valid) {
        return false;
      } else {
        this.vs.registerVehicle(this.vehicleForm.value)
         .subscribe(
           (res) => {
           console.log('Vehicle successfully registered!');
           console.log(res);
           },
           (error) => {
             console.log(error);
           }
         );
      }
    }</p>
  
  <p>}```</p>
  
  <p>The service file ie vehicle.service.ts</p>
  
  <pre><code>import { Observable, throwError } from 'rxjs';
  import { catchError, map } from 'rxjs/operators';
  import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
  
  
  @Injectable({
    providedIn: 'root'
  })
  export class VehicleService {
  
    baseUri: string = 'http://localhost:3000/vehicle';
    headers = new HttpHeaders().set('Content-Type', 'application/json');
  
    constructor(private http: HttpClient) { }
  
    registerVehicle(data): Observable&lt;any&gt;{
      console.log(data);
      const url = `${this.baseUri}/register`;
      return this.http.post(url, data);
    }
  
  }```
  
  </code></pre>