我使用Angular,TypeScript将JSON数据和JSON数据一起发送到服务器。Angular - POST上传文件
下面是我的代码:
import {Component, View, NgFor, FORM_DIRECTIVES, FormBuilder, ControlGroup} from 'angular2/angular2';
import {Http, Response, Headers} from 'http/http';
@Component({ selector: 'file-upload' })
@View({
directives: [FORM_DIRECTIVES],
template: `
<h3>File Upload</h3>
<div>
Select file:
<input type="file" (change)="changeListener($event)">
</div>
`
})
export class FileUploadCmp {
public file: File;
public url: string;
headers: Headers;
constructor(public http: Http) {
console.log('file upload Initialized');
//set the header as multipart
this.headers = new Headers();
this.headers.set('Content-Type', 'multipart/form-data');
this.url = 'http://localhost:8080/test';
}
//onChange file listener
changeListener($event): void {
this.postFile($event.target);
}
//send post file to server
postFile(inputValue: any): void {
var formData = new FormData();
formData.append("name", "Name");
formData.append("file", inputValue.files[0]);
this.http.post(this.url +,
formData ,
{
headers: this.headers
});
}
}
我怎么能改造formData
到字符串,并将其发送到服务器?我记得在AngularJS(v1)你会使用transformRequest
。
无法将数据进行this.http.post前行转换? http是一个可观察的选项,尝试搜索源代码,您可以找到一个示例https:// github。com/angular/angular/blob/8ed22ce6e7ce0e00c12b036d02627424c6b4ff35/modules/angular2/src/http/http.ts –
你对此有任何进展吗? – Canastro
GitHub上有一个悬而未决的功能请求https://github.com/angular/angular/issues/2803 – martin