Categories

Thursday, April 25, 2024
#919814419350 therichposts@gmail.com
Angular 8Angular 9Angular7

How to send files in Angular 9 application?

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

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

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