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
jQuery Image Magnifier on Mouse Hover
jQuery Image Magnifier on Mous...

In this article, we will see a jquery image magnifier on mouse hover. Using an image magnifier you can enlarge...

Read More

Jan-04-2021

How To Install TinyMCE Editor In Laravel
How To Install TinyMCE Editor...

In this article, I will give you an example of the TinyMCE editor, Tinymce editor is a rich-text open-source editor,&nbs...

Read More

Jun-18-2020

How To Install Vue 3 In Laravel 9 With Vite
How To Install Vue 3 In Larave...

In this article, we will see how to install Vue 3 in laravel 9 with vite. In the previous article, we will install...

Read More

Oct-10-2022

Laravel 11 Image Intervention Example
Laravel 11 Image Intervention...

In this article, we'll see how to use intervention images in laravel 11. Here, we'll use the intervention/i...

Read More

May-15-2024