How to return response with ng2-file-upload

房东的猫 提交于 2019-12-04 00:34:24

问题


I am using ng2-file-upload in angular 4. Is there any way to return custom data from server? How would we access it in ts file?


回答1:


You should be using uploader onSuccessItem and onErrorItem callbacks:

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
    }
}


来源:https://stackoverflow.com/questions/43516846/how-to-return-response-with-ng2-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!