In this article, we'll see how to file upload in the angular 17 tutorial. Here, we'll learn about file upload in angular 17 with the help of reactive forms. 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 file to the form group element. Then click on the submit button we'll call the API to store the file on the server.
In this tutorial, I'll guide you through the process of uploading files in Angular 17.
In this step, we'll create an angular 17 application with the following command.
ng new angular-17-file-upload
Then, we'll create a FileUpload composer using the following command.
ng g c FileUpload
Next, update the component ts file and HTML file:
src/app/image-upload/file-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-file-upload',
standalone: true,
imports: [CommonModule, FormsModule, ReactiveFormsModule, HttpClientModule],
templateUrl: './file-upload.component.html',
styleUrl: './file-upload.component.css'
})
export class FileUploadComponent {
// 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) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.myForm.patchValue({
fileSource: file
});
}
}
/**
* Write code on Method
*
* @return response()
*/
submit(){
const formData = new FormData();
const fileSourceValue = this.myForm.get('fileSource')?.value;
if (fileSourceValue !== null && fileSourceValue !== undefined) {
formData.append('file', fileSourceValue);
}
this.http.post('http://localhost:8000/upload.php', formData)
.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/file-upload/file-upload.component.html
<h1>How to File Upload in Angular 17 Tutorial - 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>
<button class="btn btn-primary" [disabled]="myForm.invalid" type="submit">Submit</button>
</form>
Now, we'll import the previously created FileUploadComponent 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 { FileUploadComponent } from './file-upload/file-upload.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet, FileUploadComponent],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'file-app';
}
In this step, we'll use the component in the HTML file.
src/app/app.component.html
<app-file-upload></app-file-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/";
$file_tmp = $_FILES['file']['tmp_name'];
$file_ext = strtolower(end(explode('.',$_FILES['file']['name'])));
$file = $folderPath . uniqid() . '.'.$file_ext;
move_uploaded_file($file_tmp, $file);
?>
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 article, we will see a jquery image magnifier on mouse hover. Using an image magnifier you can enlarge...
Jan-04-2021
In this article, I will give you an example of the TinyMCE editor, Tinymce editor is a rich-text open-source editor,&nbs...
Jun-18-2020
In this article, we will see how to install Vue 3 in laravel 9 with vite. In the previous article, we will install...
Oct-10-2022
In this article, we'll see how to use intervention images in laravel 11. Here, we'll use the intervention/i...
May-15-2024