Angular6Php

Angular Image Upload With Preview and save to folder with PHP

Angular Image Upload With Preview and save to folder with PHP - The Rich Post

angular-image-upload-save-with-php
614Views

Hello to all, welcome to therichpost.com. In this post, I came with fresh topic and I will tell you, Angular Image Upload With Preview and save to folder with PHP.

I am doing this with Angular latest version Angular 6 and with php file upload code, I will save it to folder. This is very interesting post by my point of view.

I will added the image preview code in it and here is the working picture:

Here are complete code for Angular Image Upload With Preview and save to folder with PHP :

 

1. Here is the code for app.component.ts file:
import {Component} from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public imagePath;
  constructor(private http: HttpClient) {}
  url: string;
  onSelectFile(event) { // called each time file input changes
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();
           this.imagePath = event.target.files;
       for (const file of this.imagePath) {
       const formData = new FormData();
       formData.append('image', file, file.name);
           }
       const headers = new HttpHeaders();
           headers.append('Content-Type', 'multipart/form-data');
           headers.append('Accept', 'application/json');
       this.http.post('http://localhost/mypage.php', formData).subscribe( headers, console.log(file.name) );
    
       reader.readAsDataURL(event.target.files[0]); // read file as data url
      
       reader.onload = (event) => { // called once readAsDataURL is completed
      this.url = event.target.result;
      
      }
    }
  }
}
 
2. Here is code need to app.component.html file:
<div class="jumbotron text-center">
  <h3>Angular6 Image Upload to php:</h3>
</div>
<div style="text-align:center">
<img [src]="url" height="200" *ngIf="url"> <br/>
<input type='file' (change)="onSelectFile($event)">
</div>

 

3. Here php file upload code and need to add your php file:
<?php
move_uploaded_file($_FILES["image"]["tmp_name"], "img/" . $_FILES["image"]["name"]);
?>

 4. And finally make img folder to save image.

Here you done and any query related with this post, then please ask questions and do comment below.

 

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

Positive SSL