我在角度 4 中使用 ng2-file-upload。有没有办法从服务器返回自定义数据?我们如何在 ts 文件中访问它?
问问题
11236 次
1 回答
38
您应该使用上传器 onSuccessItem 和 onErrorItem 回调:
import { Component } from '@angular/core';
import {FileUploader, FileItem, ParsedResponseHeaders} from "ng2-file-upload";
@Component({
selector: 'upload-file',
template: `
<input type="file" ng2FileSelect [uploader]="uploader">
`,
})
export class UploadFileComponent {
uploader:FileUploader;
ngOnInit(): void {
this.uploader = new FileUploader({
url: 'http://url.to/upload',
headers: [{name:'Accept', value:'application/json'}],
autoUpload: true,
});
this.uploader.onErrorItem = (item, response, status, headers) => this.onErrorItem(item, response, status, headers);
this.uploader.onSuccessItem = (item, response, status, headers) => this.onSuccessItem(item, response, status, headers);
}
onSuccessItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
let data = JSON.parse(response); //success server response
}
onErrorItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
let error = JSON.parse(response); //error server response
}
}
于 2017-04-20T11:08:25.833 回答