How to File Upload in Angular 17 Tutorial

Websolutionstuff | Apr-03-2024 | Categories : Angular

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.

Step by Step: Angular 17 File Upload Tutorial

file_upload_angular_17

 

Step 1: Create Angular 17 Project

 In this step, we'll create an angular 17 application with the following command.

ng new angular-17-file-upload

 

Step 2: Create File Upload Component

 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>

 

Step 3: Import Component

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';
}

 

Step 4: Use New Component

In this step, we'll use the component in the HTML file.

src/app/app.component.html

<app-file-upload></app-file-upload>

 

 

Step 5: Create API Endpoint

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);
     
?>
 
Step 6: Run Angular App

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:

Recommended Post
Featured Post
How to File Upload in Angular 17 Tutorial
How to File Upload in Angular...

In this article, we'll see how to file upload in the angular 17 tutorial. Here, we'll learn about file uplo...

Read More

Apr-03-2024

Google Recaptcha Example In Laravel
Google Recaptcha Example In La...

 In this tutorial I will teach you about Google Recaptcha, Google Recaptcha is used for advanced risk analysis...

Read More

Jun-10-2020

Laravel 8 Inner Join Query Example
Laravel 8 Inner Join Query Exa...

In this tutorial we will learn about laravel 8 inner join query example. Also see how to join two tables in laravel 8. I...

Read More

Nov-24-2021

How To Remove Column From Table In Laravel 10 Migration
How To Remove Column From Tabl...

In this article, we will see how to remove columns from a table in laravel 10 migration. Here, we will learn about...

Read More

Apr-26-2023