title: angular 5 image upload with multer does not uploading files
body: <p>I am trying to upload an image in angular 5 with multer using in node js. But its not doing upload. </p>
  
  <p>I am using the formData to get file details in angular 5 and sending the data to backend. But its not doing upload here.</p>
  
  <p>Here is the code what I have now </p>
  
  <p>event-create.component.html looks like this</p>
  
  <pre><code>&lt;div class="container col-md-10"&gt;
      &lt;h1 class="page-header"&gt;Create Event&lt;/h1&gt;
      &lt;form [formGroup] = "form" (ngSubmit)="onEventSubmit()"&gt;
    &lt;fieldset&gt;
      &lt;div class="form-group"&gt;
          &lt;label for="eventname"&gt;Event Name&lt;/label&gt;
        &lt;div class='input-group date col-sm-6'&gt;
          &lt;input type="text" class="form-control" autocomplete="off" placeholder="Event Name" formControlName="eventname"&gt;
        &lt;/div&gt;
      &lt;/div&gt;
  
      &lt;div class="form-group"&gt;
        &lt;label for="eventimage"&gt;Event Image&lt;/label&gt;
        &lt;div class="input-group"&gt;
          &lt;span class="input-group-btn"&gt;
            &lt;span class="btn btn-default btn-file"&gt;
              Browse… &lt;input type="file" id="eventimage" name="eventimage"  formControlName="eventimage" (change)="fileChangeEvent($event)" &gt;
  
            &lt;/span&gt;
          &lt;/span&gt;
          &lt;input type="text" class="form-control" readonly&gt;
        &lt;/div&gt;
        &lt;img id='img-upload'/&gt;
      &lt;/div&gt;
  
      &lt;input type="submit" class="btn btn-primary" value="Submit"&gt;
  
    &lt;/fieldset&gt;
  &lt;/form&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>event-create.component.ts looks like this</p>
  
  <pre><code>import { Component, OnInit } from '@angular/core';
  import { FormBuilder, FormGroup, Validators } from '@angular/forms';
  import { FormControlName } from '@angular/forms/src/directives/reactive_directives/form_control_name';
  import { EventService } from '../event.service';
  import { Response } from '@angular/http';
  
  
  @Component({
    selector: 'app-event-create',
    templateUrl: './event-create.component.html',
    styleUrls: ['./event-create.component.css']
  })
  export class EventCreateComponent implements OnInit {
  
      private file_form;
    form :  FormGroup;
    message;
    messageClass;
    processing = false;
    filesToUpload: Array&lt;File&gt; = [];
  
  
  
  
    constructor(
      private formBuilder : FormBuilder,
      private eventService : EventService,
      ) { this.createEventForm(); }
  
    createEventForm() {
      this.form = this.formBuilder.group({
        eventname: ['', Validators.required],
        eventimage: [''],
      })
    }
  
    ngOnInit() {
    }
  
    onEventSubmit() {
      const event = {
        eventname : this.form.value.eventname,
        eventimage : this.file_form,
      }
  
  
      this.eventService.addNewEvent(event).subscribe( data =&gt; {
        if( !data.success ) {
          this.messageClass = 'alert alert-danger';
        }
        else {
          this.messageClass = 'alert alert-success';
        }
      });
    }
  
  
    fileChangeEvent(event) {
      let files = event.target.files;
      if(files.length &gt; 0) {
        let file = files[0];
        let formData = new FormData();
        formData.append('eventimage', file, file.name);
        this.file_form = formData;
      }
  
    }
  
  }
  </code></pre>
  
  <p>event.service.ts looks like this</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { Http, Headers, RequestOptions } from '@angular/http';
  import { Observable } from 'rxjs';
  import { HttpClientModule } from '@angular/common/http';
  
  import { HttpClient } from "@angular/common/http";
  import 'rxjs/add/operator/map';
  
  
  @Injectable()
  export class EventService {
  
    domain = 'http://localhost:8080';
  
    headers = new Headers({ 'Content-Type': 'application/json' });
  
    constructor(
     private http: Http,
      ) { }
  
  
    addNewEvent(event) {
      return this.http.post(this.domain + '/event', {headers: this.headers}, event).map(res =&gt; res.json());
    }
  
  }
  </code></pre>
  
  <p>my express.js looks like this</p>
  
  <pre><code>/* ===================
     Import Node Modules
  =================== */
  const express = require('express');
  const app = express();
  const router = express.Router();
  
  const mongoose = require('mongoose');
  const config = require('./database');
  const path  = require('path');
  const appRoot  = require('app-root-path') ;
  
  const event = require('./routes/event.router');
  const bodyParser = require('body-parser');
  const multer = require('multer');
  
  
  const cors = require('cors');
  
  const port = process.env.PORT || 8080; // Allows heroku to set port
  
  mongoose.Promise = global.Promise;
  
  process.env.NODE_ENV = 'production';
  
  
  // Database Connection
  mongoose.connect(config.uri, {
    useMongoClient: true,
  }, (err) =&gt; {
    // Check if database was able to connect
    if (err) {
      console.log('Could NOT connect to database: ', err); // Return error message
    } else {
      console.log('Connected to ' + config.db); // Return success message
    }
  });
  
  
  app.use(cors());
  
  //app.use(bodyParser.urlencoded({ extended: false }));
  
  app.use(bodyParser.json());
  
  app.use(express.static(path.join(appRoot.path, 'dist')));
  app.use('/event', event);
  
  // Serve only the static files form the dist directory
  app.get('*', (req, res) =&gt; {
      res.sendFile(path.join(appRoot.path, 'dist/index.html'));
    });
  
  // Start Server: Listen on port 8080
  app.listen(port, () =&gt; {
    console.log('Listening on port ' + port + ' in ' + process.env.NODE_ENV + ' mode');
  });
  </code></pre>
  
  <p>event.router.js looks like this</p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var mongoose = require('mongoose');
  
  const Event = require('../../model/event.model');
  const 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())
    }
  });
  
  var upload = multer({ storage: storage }).single('eventimage');
  
  
  
  
  /* SAVE EVENT */
  //app.post('/api/image', upload.array('image', 5), (req, res, next) =&gt; {
  
  router.post('/', function(req, res, next)  {
    upload(req, res, function(err) {
      console.log(req.file); //showing undefined
      console.log(req.files); //showing undefined
      if (err) {
          // An error occurred when uploading
          throw err;
      }
      res.json({
          sucess: true,
          message: 'Image was uploaded successfully'
      });
      // Everything went fine
    });
  
  
  });
  </code></pre>
  
  <p>So can someone please tell me what I am doing wrong here. Any help and suggestions will be really appreciable.</p>
  
  <p>Here is the screenshot from chrome dev tools.</p>
  
  <p><a href="https://i.stack.imgur.com/XkNRL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XkNRL.png" alt="enter image description here"></a></p>
  
  <p>I don't know why eventimage is showing as a blank object.</p>