title: Angular 2 / Express Uploading a File to a Server
body: <p>I'm new to Angular2 and Express and I am having difficulty uploading a file to a server. I have created a basic file uploader in JS, PHP, and HTML, but can't seem to get it to work with Angular2 and Express. Any help would be appreciated. I'm more looking for an answer to file/image upload to server. :). If I'm going in the wrong direction maybe it would be easier to build a new simple project. </p>
  
  <p>At the moment I'm trying to replicate this in an angular-cli project:</p>
  
  <p><a href="https://github.com/coligo-io/file-uploader" rel="nofollow noreferrer">https://github.com/coligo-io/file-uploader</a></p>
  
  <p><strong>Problem</strong>:<br>
  I think I'm stuck at getting a post request sent to express see code below. When I test this I run ng build, and then node server.js. I can select a file but after I select a file nothing happens when it should be uploaded to the server in the 'uploads' directory.</p>
  
  <p><strong>App.Component.ts</strong></p>
  
  <pre><code>import { Component, ElementRef, ViewChild, Injectable } from '@angular/core';
  import { Http } from '@angular/http';
  
  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  
  @Injectable()
  export class AppComponent {
    title = 'app works!';
  
    @ViewChild('upload-btn') uploadbtn;
    @ViewChild('inputFile') inputFile:ElementRef;
    @ViewChild('progressBar') progressBar;
  
    constructor(private http: Http, private e1: ElementRef){}
  
    /* When button is clicked open input */
    upload(){
      console.log("clicked");
      this.inputFile.nativeElement.click();
    } // end of upload
  
    /* Process input form */
    sendToServer(){
        // Get form input
        let inputFile: HTMLInputElement = this.inputFile.nativeElement;
  
        let fileCount: number = inputFile.files.length;
  
        let formData = new FormData();
  
        console.log("File Count: " + fileCount);
  
        if( fileCount &gt; 0 ){
          for(let i = 0; i &lt; fileCount; i++){
            console.log("Count: " + i);
            formData.append('uploads[]', inputFile.files.item(i), inputFile.files.item(i).name);
          }
          console.log("Form Data: " + formData);
  
          this.http.post('http:/localhost:3000/upload', formData);
          console.log("file uploaded");
        }
  
    } // end of send to server
  
  }
  </code></pre>
  
  <p><strong>App.module.ts</strong></p>
  
  <pre><code>import { BrowserModule } from '@angular/platform-browser';
  import { NgModule } from '@angular/core';
  import { FormsModule } from '@angular/forms';
  import { HttpModule } from '@angular/http';
  
  import { AppComponent } from './app.component';
  
  @NgModule({
    declarations: [
      AppComponent
    ],
    imports: [
      BrowserModule,
      FormsModule,
      HttpModule
    ],
    providers: [],
    bootstrap: [AppComponent]
  })
  export class AppModule { }
  </code></pre>
  
  <p><strong>App.component.html</strong></p>
  
  <pre><code>&lt;div class="container"&gt;
    &lt;div class="row"&gt;
      &lt;div class="col-xs-12"&gt;
        &lt;div class="panel panel-default"&gt;
          &lt;div class="panel-body"&gt;
            &lt;span class="glyphicon glyphicon-cloud-upload"&gt;&lt;/span&gt;
            &lt;h2&gt;File Uploader&lt;/h2&gt;
            &lt;h4&gt;coligo.io&lt;/h4&gt;
            &lt;div class="progress"&gt;
              &lt;div #progressBar class="progress-bar" role="progressbar"&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;button (click)="upload()" class="btn btn-lg upload-btn" type="button"&gt;Upload File&lt;/button&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  
  &lt;input #inputFile  (change)="sendToServer()" id="upload-input" type="file" name="uploads[]" multiple="multiple"&gt;&lt;br/&gt;
  </code></pre>
  
  <p><strong>Server.js</strong></p>
  
  <pre><code>var express = require('express');
  var app = express();
  var path = require('path');
  var formidable = require('formidable');
  var fs = require('fs');
  
  app.use(express.static(path.join(__dirname, 'dist')));
  
  app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'dist/index.html'));
  });
  
  app.post('/upload', function(req, res){
    console.log("Server Hit");
    // create an incoming form object
    var form = new formidable.IncomingForm();
  
    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;
  
    // store all uploads in the /uploads directory
    form.uploadDir = path.join(__dirname, '/uploads');
  
    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    form.on('file', function(field, file) {
      fs.rename(file.path, path.join(form.uploadDir, file.name));
    });
  
    // log any errors that occur
    form.on('error', function(err) {
      console.log('An error has occured: \n' + err);
    });
  
    // once all the files have been uploaded, send a response to the client
    form.on('end', function() {
      res.end('success');
    });
  
    // parse the incoming request containing the form data
    form.parse(req);
  
  });
  
  var server = app.listen(3000, function(){
    console.log('Server listening on port 3000');
  });
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/YWWfQ.png" rel="nofollow noreferrer">File Structure for attempt 2</a></p>
  
  <p>Thanks for the help. I really appreciate it.</p>