我对Angular 2很新,请考虑一下。
我遇到使用角度2将文件上传到节点服务器的问题。使用邮递员可以正常工作:
邮差快照:
但是,当我使用Angular2应用程序将文件发送到服务器时,它什么都不做:
Angular 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>
Angular 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' } });
}
}
当然,我必须在这里遗漏一些东西。我请求大家,请提供一些解决方案。
答案 0 :(得分:1)
您必须创建formData才能上传文件。以下是示例代码。
import re
stripChar = input('Enter character to strip: ')
context = input('Enter string to strip: ')
stripContext = None
def strip(char, string):
if stripChar == "":
regsp = re.compile(r'^\s+|\s+$')
stripContext = regsp.sub("", context)
return stripContext
else:
stripContext = re.sub(r'^(char)+', "", string)
return stripContext
print(strip(stripChar, context))
答案 1 :(得分:0)
我认为你的问题是关于标题。
试试这个:
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/x-www-form-urlencoded' } });
}
}
如果您检查PostMan屏幕截图,则提供的标题完全相同。是上传文件的常用方法