2017-02-15 100 views
1

我正在製作一個簡單的文件上傳腳本,並且只能找到基於input(change)事件的工作示例。即 - https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/Angular 2 - 文件上傳 - 如何訪問文件?

<input type="file" id="userfile" class="form-control" 
(change)="fileChangeEvent($event)" name='userfile'> 

This works。這很好。

但是,如果我嘗試綁定文件輸入到ngModel它不起作用。

模板

<form class="form-signin" (ngSubmit)="onSubmit(fileForm.value)" #fileForm="ngForm"> 
<input type="file" id="userfile" class="form-control" 
[(ngModel)]="fileUpload.userfile" name='userfile'> 
<input type="text" id="random" class="form-control" 
[(ngModel)]="fileUpload.random" name="random"> 

<button class="btn btn-lg btn-primary btn-block" type="submit">Upload File</button> 
</form> 

component.ts

onSubmit(data){ 
    console.log("Submitted"); 
    console.log(data); 
    } 

只有數據在random輸入設置會顯示出來。沒有文件放置在文件輸入將顯示出來,只有(在我的ngModel和打印出來的數據)(undefined)onSubmit(data)

+0

[Angular 2 File input from input type = file]可能重複(http://stackoverflow.com/questions/35399617/angular-2-file-upload-from-input-type-file) – Adam

回答

1

我也有問題在Angular 2中如何處理文件,所以我選擇了低這種技術方法可以支持Angular 2形式。

我的模板看起來像這樣。

<input class="field" type="file" (change)="setFile($event)" /> 

並訪問我的文件,我用:

private setFile(event) { 
    this._files = event.srcElement.files; 
} 

然後,您可以使用這些文件。

請記住,在Angular 2中上傳多部分文件數據也不起作用(上次我選中),因此您可能不得不使用手動XHR請求而不是HTTP提供程序。 See this answer for details about that