Menu Close

Upload Image With Preview in Angular 12

Codeamend

In this tutorial, we will see how to upload images in angular 12 app using react form with formGroup. 

Follow the below steps to upload image with preview in Angular 12

Create a New Angular Application

By using the following command on your command prompt to install the angular app.

ng new image-upload 

Go to the new project directory using the below command:

cd image-upload 

Import module

Next, Open the app.module.ts file and import the following modules on it.

  1. HttpClientModule
  2. FormsModule
  3. ReactiveFormsModule
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
   
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { } 

Add the code on view file

Here, Create the simple reactive form with input element and image tag. Then, update the codes on the src/app/app.component.html file.

<h1>Angular 12 Image Upload with Preview</h1>
   
<form [formGroup]="myForm" (ngSubmit)="submit()">
     
    <div class="form-group">
        <label for="name">Name</label>
        <input formControlName="name" id="name" type="text" class="form-control">
        <div *ngIf="f.name.touched && f.name.invalid" class="alert alert-danger">
            <div *ngIf="f.name.errors && f.name.errors.required">Name is required.</div>
            <div *ngIf="f.name.errors && f.name.errors.minlength">Name should be 3 character.</div>
        </div>
    </div>
    
    <div class="form-group">
        <label for="file">File</label>
        <input formControlName="file" id="file" type="file" class="form-control" (change)="onFileChange($event)">
        <div *ngIf="f.file.touched && f.file.invalid" class="alert alert-danger">
            <div *ngIf="f.file.errors && f.file.errors.required">File is required.</div>
        </div>
    </div>
    
    <img [src]="imageSrc" *ngIf="imageSrc" style="height: 300px;width:300px">
        
    <button class="btn btn-primary" type="submit">Submit</button>
</form> 

Use component ts file

Go to the src/app directory and open app.component.ts file. Then add formGroup and formControl elements on it.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormControl, Validators} from '@angular/forms';
    
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   imageSrc: string = '';
   myForm = new FormGroup({
    name: new FormControl('', [Validators.required, Validators.minLength(3)]),
    file: new FormControl('', [Validators.required]),
    fileSource: new FormControl('', [Validators.required])
  });
  
  constructor(private http: HttpClient) { }
    
  get f(){
    return this.myForm.controls;
  }
   
  onFileChange(event:any) {
    const reader = new FileReader();
    
    if(event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      reader.readAsDataURL(file);
    
      reader.onload = () => {
   
        this.imageSrc = reader.result as string;
     
        this.myForm.patchValue({
          fileSource: reader.result
        });
   
      };
   
    }
  }
   
  submit(){
    console.log(this.myForm.value);
    this.http.post('http://localhost/img/upload.php', this.myForm.value)
      .subscribe(res => {
        console.log(res);
        alert('Uploaded Successfully.');
      })
  }
} 

Create upload.php file

Create the upload.php file and add the following codes on it. This will help to add images on the server from the angular 12 app.

<?php
  
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: PUT, GET, POST");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
      
    $folderPath = "upload/";
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);
      
    $image_parts = explode(";base64,", $request->fileSource);
      
    $image_type_aux = explode("image/", $image_parts[0]);
      
    $image_type = $image_type_aux[1];
      
    $image_base64 = base64_decode($image_parts[1]);
      
    $file = $folderPath . uniqid() . '.png';
      
    file_put_contents($file, $image_base64);
  
?> 

Start the Angular and PHP server

In this step, Enter the following command on your command prompt to start the Angular app and PHP server(XAMPP).

ng serve 

Important Note

You can improve your style by using the bootstrap on the angular applications. Run the below command to install the angular social login package.

npm i bootstrap 

Then open angular.json file and add Bootstrap module CSS path in the styles array like below.

"styles": [
     "node_modules/bootstrap/dist/css/bootstrap.min.css",
     "src/styles.scss"
] 
Posted in Angular, Codeamend

You can also read...