Upload File With Angular 4 and Save in Server .net Backend
Uploading Files With ASP.NET Core and Angular
This article discuss about uploading files from an Athwart application to ASP.Net Core backend. First you demand to create an ASP.NET Core Athwart project. Once it is done, you need to create an angular component. And so you tin modify the backend implementation.
Creating an Angular component
To create an angular component, you lot need to run the post-obit command - ng generate component fileupload --skip-import --skip-tests -s
. Next you demand to modify the typescript file - fileupload.component.ts
similar this.
upload ( files ) { if ( files . length === 0 ) render ; const formData = new FormData (); for ( const file of files ) { formData . append ( file . name , file ); } const uploadReq = new HttpRequest ( ' POST ' , this . baseUrl + ' FileManagement/upload ' , formData , { reportProgress : true , }); this . http . request ( uploadReq ). subscribe ( event => { if ( event . type === HttpEventType . UploadProgress ) { this . progress = Math . round ( 100 * event . loaded / outcome . total ); }; }); }
In the above code, when a user scan files, the on alter event will be fired. And and so upload the file with httpclient
using FormData object. And in the fileupload.component.html
yous need to change and include HTML like this.
<div grade= "grade-group" > <label for= "flick" >Motion picture</label> <div class= "custom-file" > <input #file type= "file" id= "customFile" have= ".jpg,.png,.gif" multiple (change)= "upload(file.files)" /> <label class= "custom-file-characterization" for= "customFile" >Choose file</label> </div> </div> <div class= "progress" > <div class= "progress-bar" role= "progressbar" [ style.width. % ]= "progress" ></div> </div>
In the next section yous volition learn how to read and save in ASP.NET Core.
Implementing the backend
In ASP.Net Core y'all can create a controller, and create an activity method. In the action method, you can utilise Request.Course.Files
to read the uploaded files with Form Data from Athwart client.
[ HttpPost ] [ Route ( "upload" )] public async Task < IActionResult > Upload () { var files = Request . Form . Files ; foreach ( var file in files ) { var blobContainerClient = new BlobContainerClient ( "UseDevelopmentStorage=true" , "images" ); blobContainerClient . CreateIfNotExists (); var containerClient = blobContainerClient . GetBlobClient ( file . FileName ); var blobHttpHeader = new BlobHttpHeaders { ContentType = file . ContentType }; await containerClient . UploadAsync ( file . OpenReadStream (), blobHttpHeader ); } return Ok (); }
The in a higher place code is using the Asking.Form.Files
options. Y'all can also employ the Request.ReadFormAsync()
method which helps you to read the files asynchronously, here is the code for reading the file asynchronously with the help of Request.ReadFormAsync()
method.
[ HttpPost ] [ Road ( "upload" )] public async Task < IActionResult > Upload () { var formCollection = await Request . ReadFormAsync (); var files = formCollection . Files ; foreach ( var file in files ) { var blobContainerClient = new BlobContainerClient ( "UseDevelopmentStorage=true" , "images" ); blobContainerClient . CreateIfNotExists (); var containerClient = blobContainerClient . GetBlobClient ( file . FileName ); var blobHttpHeader = new BlobHttpHeaders { ContentType = file . ContentType }; look containerClient . UploadAsync ( file . OpenReadStream (), blobHttpHeader ); } return Ok (); }
ASP.NET Cadre also supports File Upload with the assistance of grade binding. Here is the implementation in the ASP.NET Cadre controller.
[ HttpPost ] [ Road ( "createprofile" )] public async Chore < IActionResult > CreateProfile ([ FromForm ] Contour profile ) { if ( ModelState . IsValid ) { var tempProfile = contour ; render Ok (); } return BadRequest (); }
And here is the Profile
class.
public class Profile { [ Required ] public string Name { get ; ready ; } [ Required ] public string Email { get ; set ; } [ Required ] public IFormFile Picture { get ; fix ; } }
And from Angular customer y'all can employ the Angular forms. Here is the Athwart code which upload and submit the data to server.
const formData = new FormData (); for ( const cardinal of Object . keys ( this . profileForm . value )) { const value = this . profileForm . value [ key ]; formData . append ( cardinal , value ); } this . http . post ( this . baseUrl + ' FileManagement/createprofile ' , formData , { reportProgress : true , observe : ' events ' }). subscribe ( outcome => { if ( consequence . blazon === HttpEventType . UploadProgress ) { this . progress = Math . circular (( 100 * issue . loaded ) / event . total ); } if ( effect . type === HttpEventType . Response ) { console . log ( event . body ); this . profileForm . reset (); } });
And at that place is one specific code block which helps to populate the File value to Angular form control. Here is the code, which triggered on the change event of File Upload control.
onFileChanged ( event ) { if ( event . target . files . length > 0 ) { const file = event . target . files [ 0 ]; this . labelImport . nativeElement . innerText = file . name ; this . profileForm . patchValue ({ motion-picture show : file , }); } }
And here is the HTML code for the Class
<class class= "needs-validation" novalidate [formGroup]= "profileForm" (ngSubmit)= "onSubmit()" > <div class= "grade-grouping" > <label for= "name" >Name</label> <input type= "text" formControlName= "name" course= "form-control" id= "name" [ngClass]= "{ 'is-invalid': class.name.invalid && (form.proper name.muddy || grade.name.touched) }" > <div class= "invalid-feedback" *ngIf= "grade.name.touched && form.name.invalid" > <div *ngIf= "grade.name.errors.required" >Proper name is required.</div> <div *ngIf= "form.proper name.errors.minlength" >Proper name should be 2 graphic symbol.</div> </div> </div> <div grade= "form-group" > <label for= "electronic mail" >Email</characterization> <input type= "email" formControlName= "email" class= "grade-control" id= "email" [ngClass]= "{ 'is-invalid': form.email.invalid && (form.email.muddy || form.electronic mail.touched) }" > <div class= "invalid-feedback" *ngIf= "form.e-mail.touched && form.email.invalid" > <div *ngIf= "course.email.errors.required" >Email is required.</div> <div *ngIf= "form.e-mail.errors.email" >Invalid email.</div> </div> </div> <div grade= "course-grouping" > <label for= "picture" >Picture</label> <div course= "custom-file" > <input type= "file" class= "custom-file-input" id= "customFile" (modify)= "onFileChanged($issue)" accept= ".jpg,.png,.gif,.pdf,.xls,.xlsx,.doc,.docx,.ppt,.pptx" > <label course= "custom-file-label" #labelImport for= "customFile" >Cull file</label> </div> <div course= "invalid-feedback" *ngIf= "grade.film.touched && course.pic.invalid" > <div *ngIf= "form.picture.errors.required" >Picture is required.</div> </div> </div> <input blazon= "submit" value= "Submit" [disabled]= "profileForm.invalid" course= "btn btn-primary" /> </form>
Here is the screenshot of the application running.
This mode yous can implement File Upload from Angular to ASP.NET Core and how to store them in Azure Blob storage. Y'all can utilize the model binding implementation if you are planning to use upload a file along with other form fields like name or email.
Happy Programming :)
Source: https://dotnetthoughts.net/upload-files-dot-net-core-angular/
0 Response to "Upload File With Angular 4 and Save in Server .net Backend"
إرسال تعليق