Menu

Uploading files from Angular 2 and ASP.NET Core Web API – Part 1

Project that I am working on need to upload some files, I have used ng2-file-upload for my client side, and on server side I am using ASP.NET Core Web API. This is the part 1 demonstrating how to upload the file from Angular 2. Please check out part 2 for the ASP.NET Core server side logic.

First install the npm on your angular 2 project

npm install ng2-file-upload --save

in your app.module.ts file add the reference like below

.......
import { FileUploadModule } from 'ng2-file-upload';
.......

and import as part of the module imports

imports: [
.....,
FileUploadModule
]

component.html html looks like below

<form method="post" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group">
<label>Identification to upload</label>
<input type="file" ng2FileSelect [uploader]="uploader" />
</div>
</div>
<div class="box-footer">
<button type="button" class="btn btn-primary" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">Upload</button>
</div>
</form>

component.ts looks like this

.....
import { FileUploader } from 'ng2-file-upload';
.....

export class DetailsComponent implements OnInit {
  form: FormGroup;
  ....
  public uploader: FileUploader;
  constructor(public fb: FormBuilder,
  ......) {

  }

  ngOnInit() { 
    this.initUploader();
    this.getVerificationTypes();
  }

  initUploader() {
    this.uploader = new FileUploader({ url: "/api/Attachments/upload", authToken: 'Bearer ' + this.storageService.get('id_token') });
    this.uploader.onBuildItemForm = (item, form) => { form.append("attachmentId", this.attachmentId); };
    this.uploader.onCompleteAll = () => {
       // hide loader & reaload data if needed
    };
  } 
}

Please check out part 2 for the ASP.NET Core server side logic.

Leave a comment