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
Dependent Dropdown In Laravel 9 Vue JS
Dependent Dropdown In Laravel...

In this article, we will see a dependent dropdown in laravel 9 vue js. Here, we will learn how to create a dependent dro...

Read More

Dec-15-2022

How To Disable Future Date In jQuery Datepicker
How To Disable Future Date In...

In this tutorial, we will see how to disable future dates in jquery datepicker. In the date picker, today's dat...

Read More

Jun-17-2022

Laravel 9 Image Upload In Summernote Editor
Laravel 9 Image Upload In Summ...

In this article, we will see laravel 9 image upload in summernote editor. there are many editor available in l...

Read More

Mar-24-2022

VPS Servers - Take a Step Ahead to More Growth
VPS Servers - Take a Step Ahea...

It is the poor hosting that is causing you so many issues. If you upgrade to advanced hosting based on your website need...

Read More

Apr-08-2022