Using the new Angular 4.3 HttpClient, how can I upload and access files in an ASP.NET Core 2.0 Controller while reporting upload progress to the client?
This article discuss about uploading files from an Angular application to ASP.NET Core backend. First you need to create an ASP.NET Core Angular project. Once it is done, you need to create an angular component. And then you can modify the backend implementation.
If you want to download our finished project, you can do that from Upload Files .NET Core Angular Finished Project. We are going to divide this article into the following sections:
First you need to create an ASP.NET Core Angular project. Once it is done, you need to create an angular component. And then you can modify the backend implementation. To create an angular component, you need to run the following command - ng generate component fileupload --skip-import --skip-tests -s.
In the next section you will learn how to read and save in ASP.NET Core. In ASP.NET Core you can create a controller, and create an action method. In the action method, you can use Request.Form.Files to read the uploaded files with Form Data from Angular client. The above code is using the Request.Form.Files options.
Here is a working example to get started:
<input #file type="file" multiple (change)="upload(file.files)" />
<span *ngIf="uploadProgress > 0 && uploadProgress < 100">
{{uploadProgress}}%
</span>
import { Component } from '@angular/core';
import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http'
@Component({
selector: 'files',
templateUrl: './files.component.html',
})
export class FilesComponent {
public uploadProgress: number;
constructor(private http: HttpClient) { }
upload(files) {
if (files.length === 0)
return;
const formData = new FormData();
for (let file of files)
formData.append(file.name, file);
const req = new HttpRequest('POST', `api/files`, formData, {
reportProgress: true,
});
this.http.request(req).subscribe(event => {
if (event.type === HttpEventType.UploadProgress)
this.uploadProgress = Math.round(100 * event.loaded / event.total);
else if (event instanceof HttpResponse)
console.log('Files uploaded!');
});
}
}
[HttpPost, DisableRequestSizeLimit, Route("api/files")]
public async Task UploadFiles()
{
var files = Request.Form.Files; // now you have them
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With