In this article, we'll see how to image upload with a preview in angular 17. Here, we'll learn about the angular 17 upload image with a preview of the image. For this, we'll set angular 17 to create components and also create an API to upload images.
In this guide, we'll create a reactive form using a form group and on the change event, we'll add the image file to the form group element. Then click on the submit button we'll call the API to store the image on the server.
In this step, we'll create an angular 17 application with the following command.
ng new angular-17-image-upload
Then, we'll create an ImageUpload composer using the following command.
ng g c ImageUpload
Next, update the component ts file and HTML file:
src/app/image-upload/image-upload.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { HttpClientModule, HttpClient } from '@angular/common/http';
@Component({
selector: 'app-image-upload',
standalone: true,
imports: [CommonModule, FormsModule, ReactiveFormsModule, HttpClientModule],
templateUrl: './image-upload.component.html',
styleUrl: './image-upload.component.css'
})
export class ImageUploadComponent {
imageSrc: string = '';
// Declare form
myForm = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(3)]),
file: new FormControl('', [Validators.required]),
fileSource: new FormControl('', [Validators.required])
});
// created constructor
constructor(private http: HttpClient) { }
/**
* Write code on Method
*
* @return response()
*/
get f(){
return this.myForm.controls;
}
/**
* Write code on Method
*
* @return response()
*/
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 as string
});
};
}
}
/**
* Write code on Method
*
* @return response()
*/
submit(){
console.log(this.myForm.value);
this.http.post('http://localhost:8000/upload.php', this.myForm.value)
.subscribe(res => {
console.log(res);
alert('Uploaded Successfully.');
})
}
}
Then, we'll update our HTML file. In this, we'll create a simple form for uploading images and add a submit button.
src/app/image-upload/image-upload.component.html
<h1>How to Image Upload with Preview in Angular 17 - Websolutionstuff</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:500px">
<button class="btn btn-primary" [disabled]="myForm.invalid" type="submit">Submit</button>
</form>
Now, we'll import the previously created ImageUploadComponent to the app.component.ts file.
src/app/app.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { ImageUploadComponent } from './image-upload/image-upload.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet, ImageUploadComponent],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'image-app';
}
In this step, we'll use the component in the HTML file.
src/app/app.component.html
<app-image-upload></app-image-upload>
Next, we'll create an API file using PHP. So, create an upload.php file with an upload folder and run with a different port.
upload.php
<?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);
?>
Now, we'll run the angular 17 application using the following command.
ng serve
Run PHP API:
php -S localhost:8000
You might also like:
In this example we will see autocomplete search using bootstrap typeahead js.Typeahead search is a method for progr...
Jun-09-2021
In this article, we will see how to add the bootstrap 5 modal in laravel 10. Here, we will learn about the bootstra...
Apr-12-2023
Hello, laravel web developers! In this article, we'll see how to image upload in laravel 11 Livewire. Here, we'l...
Jun-07-2024
In this article, we will see how to send email using markdown mailable laravel 9. we will learn laravel 9 to s...
Aug-05-2022