我对Angular 2很陌生,请考虑一下。
我在使用angular 2将文件上载到节点服务器时遇到问题。使用邮递员可以很好地工作:
邮差快照:
enter image description here
但是,当我使用Angular2应用程序向服务器发送文件时,它不会执行任何操作:
角度HTML组件
<label for="file1">Upload PDF version: </label>
<form class="form-inline">
<div class="form-group">
<input type="file" id="file1" #abc name="fileToUpload" class="form-control" placeholder="Upload PDF">
</div>
<button class="btn btn-primary" type="submit" (click)="onUpload(abc)">Upload</button>
</form>
角度TS组件:
import { Component, OnInit } from '@angular/core';
import { UploadService } from './upload.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.css']
})
export class UploadComponent implements OnInit {
// file1 = document.getElementById("file1");
constructor(private uploadService: UploadService) { }
ngOnInit() {
}
onUpload = (file: File) => {
this.uploadService.uploadfile(file)
.subscribe((res) => {
console.log(res);
},
(err) => {
console.log(err);
});
}
}
服务组件:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class UploadService {
constructor(private http: HttpClient) {
}
uploadfile(file: File): Observable<File> {
console.log(file);
return this.http.post<File>("http://localhost:3000/fileupload", file, { headers: { 'Content-Type': 'application/json' } });
}
}
当然,我一定错过了什么。请大家提供一些解决方案。