2017-04-20 22 views

回答

13

您應該使用上傳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 
 
    } 
 
}

+0

謝謝。它的工作... –

+2

@TanviShah請接受這個答案,如果你發現它是正確的 – karser

+0

這樣的工作,但我有一個更多的問題,如何處理當用戶第二次上傳一些文件後,第一次onSuccessItem函數再也不會調用? –