问题描述
我使用Angular2,打字稿发送一个文件,使用JSON数据一起到服务器。
I'm using Angular2, TypeScript to send a file, along with JSON Data to a server.
下面是我的code:
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为字符串,并将其发送到服务器。我记得在Angular1你会使用transformRequest。
How can i transform the formData to String and send it to the server. I remember in Angular1 you would use transformRequest.
我AP preciate任何指导或建议。
I appreciate Any guidance or advice.
推荐答案
看我的code,但要注意。我使用异步/的await,因为最新的Chrome测试版可以读取任何ES6 code,它通过打字稿得到与编译。所以,你必须更换asyns / AWAIT 。然后()
。
Look at my code, but be aware. I use async/await, because latest Chrome beta can read any es6 code, which gets by TypeScript with compilation. So, you must replace asyns/await .then()
.
输入更改处理:
/**
* @param fileInput
*/
public psdTemplateSelectionHandler (fileInput: any){
let FileList: FileList = fileInput.target.files;
for (let i = 0, length = FileList.length; i < length; i++) {
this.psdTemplates.push(FileList.item(i));
}
this.progressBarVisibility = true;
}
提交处理程序:
public async psdTemplateUploadHandler (): Promise<any> {
let result: any;
if (!this.psdTemplates.length) {
return;
}
this.isSubmitted = true;
this.fileUploadService.getObserver()
.subscribe(progress => {
this.uploadProgress = progress;
});
try {
result = await this.fileUploadService.upload(this.uploadRoute, this.psdTemplates);
} catch (error) {
document.write(error)
}
if (!result['images']) {
return;
}
this.saveUploadedTemplatesData(result['images']);
this.redirectService.redirect(this.redirectRoute);
}
FileUploadService。这项服务也存储在进步$财产上传进度,而在其他地方,你可以订阅它,并获得新的价值每500毫秒。
FileUploadService. That service also stored uploading progress in progress$ property, and in other places, you can subscribe on it and get new value every 500ms.
import { Component } from 'angular2/core';
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
@Injectable()
export class FileUploadService {
/**
* @param Observable<number>
*/
private progress$: Observable<number>;
/**
* @type {number}
*/
private progress: number = 0;
private progressObserver: any;
constructor () {
this.progress$ = new Observable(observer => {
this.progressObserver = observer
});
}
/**
* @returns {Observable<number>}
*/
public getObserver (): Observable<number> {
return this.progress$;
}
/**
* Upload files through XMLHttpRequest
*
* @param url
* @param files
* @returns {Promise<T>}
*/
public upload (url: string, files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
FileUploadService.setUploadUpdateInterval(500);
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
/**
* Set interval for frequency with which Observable inside Promise will share data with subscribers.
*
* @param interval
*/
private static setUploadUpdateInterval (interval: number): void {
setInterval(() => {}, interval);
}
}
这篇关于Angular2后上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!