Angular 2 / Express将文件上传到服务器

时间:2017-02-15 16:14:09

标签: angular express file-upload

我是Angular2和Express的新手,我无法将文件上传到服务器。我已经在JS,PHP和HTML中创建了一个基本的文件上传器,但似乎无法使用Angular2和Express。任何帮助,将不胜感激。我正在寻找文件/图像上传到服务器的答案。 :)。如果我走向错误的方向,那么构建一个新的简单项目会更容易。

目前我正试图在angular-cli项目中复制它:

https://github.com/coligo-io/file-uploader

问题
我想我一直在发送邮件请求发送快递,请参阅下面的代码。当我测试这个时,我运行构建,然后运行node server.js。我可以选择一个文件但是在我选择一个文件后,当它应该上传到'uploads'目录中的服务器时没有任何反应。

App.Component.ts

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 > 0 ){
        for(let i = 0; i < 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

}

App.module.ts

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 { }

App.component.html

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <div class="panel panel-default">
        <div class="panel-body">
          <span class="glyphicon glyphicon-cloud-upload"></span>
          <h2>File Uploader</h2>
          <h4>coligo.io</h4>
          <div class="progress">
            <div #progressBar class="progress-bar" role="progressbar"></div>
          </div>
          <button (click)="upload()" class="btn btn-lg upload-btn" type="button">Upload File</button>
        </div>
      </div>
    </div>
  </div>
</div>

<input #inputFile  (change)="sendToServer()" id="upload-input" type="file" name="uploads[]" multiple="multiple"><br/>

Server.js

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');
});

File Structure for attempt 2

感谢您的帮助。我真的很感激。

1 个答案:

答案 0 :(得分:0)

您需要subscribe以角度

请求

e.g。

this.http.post('http:/localhost:3000/upload', formData)
    .subscribe();