Home Angular 8 How to send files in Angular 9 application?

How to send files in Angular 9 application?

by therichpost
0 comments
send file in angular 9

Hello to all, welcome on therichpost.com. In this post, I will tell you, How to send files in Angular 9 application?

Post Working:

In post, I am sending files or images to my laravel backend in my Angular 9 application.

Here is the code snippet and please use carefully:

1. Here is my HTML code for app.component.ts file:

<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<input type="file" #fileupload [(ngModel)]="myFile" name="myFile" (change)="fileEvent($event)"/>
<button>Upload Image</button>

 

2. Here is my code for app.component.ts file:

...
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {NgForm} from '@angular/forms';
...

filedata:any;

//File onChange event, where I am getting the file details
fileEvent(e){
        this.filedata = e.target.files[0];
    }

constructor(private http: HttpClient) {}

//Form Submit Function
onSubmit(f: NgForm) {

          var myFormData = new FormData();
          const headers = new HttpHeaders();
          headers.append('Content-Type', 'multipart/form-data');
          headers.append('Accept', 'application/json');

          // store file details into formdata
          myFormData.append('image', this.filedata);

          //HTTP Angular service, which will send call to Laravel API With headers and myformdata
          this.http.post('http://localhost/blog/public/api/sample-restful-apis', myFormData, { headers: headers }).subscribe(data => {
          console.log(data);
      });
        
      }

 

3. Code for app.module.ts file:

...
import { HttpClientModule } from '@angular/common/http';
import { FormsModule }   from '@angular/forms';
...

...
imports: [
    ...
    HttpClientModule,
    FormsModule,
    ...
  ],
...

 

In this post, I just showed, how to send files or images in Angular 9. I have used FORMDATA to send files because it is easy and clean way to send our data.

If you have any kind of query then please do comment below.

Jassa

Thank you

You may also like

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.