简体   繁体   English

如何使用ng2-file-upload返回响应

[英]How to return response with ng2-file-upload

I am using ng2-file-upload in angular 4. Is there any way to return custom data from server? 我在角度4使用ng2-file-upload。有没有办法从服务器返回自定义数据? How would we access it in ts file? 我们如何在ts文件中访问它?

You should be using uploader onSuccessItem and onErrorItem callbacks: 您应该使用onloader 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 } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM