Home Angular6 Angular Image Upload With Preview and save to folder with PHP

Angular Image Upload With Preview and save to folder with PHP

by therichpost
2 comments
angular-image-upload-save-with-php

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.

 

You may also like

2 comments

ashish April 21, 2021 - 6:59 am

how to post image into mysql datbase using angular 8 or 9 or 10 and php
and how to get img

Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.