2016-09-28 91 views
2

我正在創建一個angular2項目,並且我正在使用ng2-uploader作爲文件上傳的插件。我想抓住一個div,並在同一時間我想要在div內的上傳按鈕。選擇一個文件上傳後,我得到的錯誤爲 TypeError:無法將undefined或null轉換爲對象如何解決:TypeError:無法將undefined或null轉換爲對象

HTML代碼:

<div [hidden]="!onUpload" ngFileDrop [options]="options" (onUpload)="handleUpload($event)" [ngClass]="{'file-over': hasBaseDropZoneOver}" (onFileOver)="fileOverBase($event)"> 
    <input type="file" ngFileSelect [options]="options" (onUpload)="handleUpload($event)"> 
    <p><span>Response: {{ uploadFile | json }}</span></p> 
</div> 

組件是:

import { Component, OnInit, NgModule, NgZone } from '@angular/core'; 

@Component({ 
    selector: 'app-fileselect', 
    templateUrl: './fileselect.component.html', 
    styleUrls: ['./fileselect.component.css'] 
}) 

export class FileSelectComponent implements OnInit { 
    zone: NgZone; 
    hasBaseDropZoneOver: boolean = false; 
    basicProgress: number = 0; 
    uploadFile: any; 

constructor() { 
    this.zone = new NgZone({ enableLongStackTrace: false });//file upload  
    } 

options: Object = { 
    url: 'http://localhost:4200/assets/documents' 
    }; 

handleUpload(data): void { 
    if (data && data.response) { 
     data = JSON.parse(data.response); 
     this.uploadFile = data; 
     this.zone.run(() => { 
     this.basicProgress = data.progress.percent; 
     }); 
    } 
    } 

fileOverBase(e: any): void { 
     this.hasBaseDropZoneOver = e; 
     } 
    } 
+0

我也面對這個問題,讓我知道html的完整結構, 主要是這個上傳按鈕的外部div。 –

+0

當然我會更新我的問題 – sainu

回答

2

響應:{{uploadFile | json}}

由於這種結構,當你使用輸入文件上傳項目時,它會自動觸發父div('ngFileDrop')。所以它會調用空數據的函數。這個過程會造成錯誤。

所以你可以做一件事,只需將輸入按鈕放在父div的旁邊並嘗試。它肯定會起作用。

<div [hidden]="!onUpload" ngFileDrop [options]="options" (onUpload)="handleUpload($event)" [ngClass]="{'file-over': hasBaseDropZoneOver}" (onFileOver)="fileOverBase($event)">  
     <p><span>Response: {{ uploadFile | json }}</span></p> 
    </div> 
    <input type="file" ngFileSelect [options]="options" (onUpload)="handleUpload($event)"> 

現在你可以使用一些css來定位div內的輸入按鈕。

只需檢查一下。

+0

謝謝@aswin – sainu

1

在HTML代碼中你錯過了一個"之後選擇:

你寫道:

<input type="file" ngFileSelect [options]="options (onUpload)="handleUpload($event)"> 

你應該寫:

<input type="file" ngFileSelect [options]="options" (onUpload)="handleUpload($event)"> 
+0

對不起@StephaneM。這是我的錯誤。其實在我的程序裏'''有。 – sainu

相關問題