1

I am making a simple file upload script and have only been able to find working examples that are based off of an input's (change) event. I.e. - https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/

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

This works. And that's great.

However if I try to bind a file input to an ngModel it doesn't work.

template

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

Only the data set in the random input will show up. No files placed in the file input will show up, only as (undefined) in both my ngModel and printing out the data from onSubmit(data)

1

1 Answer 1

2

I also had issues with how files were handled in Angular 2, so I opted for the low-tech approach that side-steps Angular 2 forms.

My template looks like this.

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

And to access my files, I use:

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

You can then use those files.

Keep in mind uploading multi-part file data in Angular 2 also doesn't work (last time I checked), so you may have to use manual XHR request rather than the HTTP provider. See this answer for details about that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.