Brian
Brian

Reputation: 5

Upload Image in Angular 8 to PHP service

I have my code in Angular 8

<form [formGroup]="upload" (ngSubmit)="sendParameters()">
            <div class="input-image">
                <p>
                    <input id="upload-image" formControlName="image" type="file" name="file" accept="image/*" (change)="onFileChanged($event.target.files)">
                </p>
            </div>
            <div class="input-active">
                <p>
                    <mat-slide-toggle class="example-margin" color="primary" (change)="onChange($event)"> STATUS</mat-slide-toggle>
                </p>
            </div>

            <div class="button">
                <p>
                    <button mat-raised-button>UPLOAD</button>
                </p>
            </div>
        </form>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ConnectionsService } from '../../connections.service';
import { AuthenticationService } from '../../authentication.service';
import { LocationStrategy } from '@angular/common';
import { User } from '../../Model/user';
import { Subscription } from 'rxjs';
import { ToastrService } from 'ngx-toastr';

class ImageSnippet {
  constructor(public src: string, public file: File) {}
}

@Component({
  selector: 'app-subir-imagen',
  templateUrl: './subir-imagen.component.html',
  styleUrls: ['./subir-imagen.component.css']
})
export class SubirImagenComponent implements OnInit {

  public currentUser: User;
  public currentUserSubscription: Subscription;
  public users: User[] = [];

  public upload;
  public selectedFile: File = null;
  public status: number;
  public idEmpleado: number;
  public loading = false;

  constructor(
    public formBuilder: FormBuilder,
    public locationStrategy: LocationStrategy,
    public authenticationService: AuthenticationService,
    public service: ConnectionsService,
    public toastr: ToastrService) {
      this.currentUserSubscription = this.authenticationService.currentUser.subscribe(user => {
        this.currentUser = user;
      });
    }

  ngOnInit() {
    this.idEmpleado = this.currentUser.id || this.currentUser[0].id;
    this.upload = this.formBuilder.group({
      image: ['', Validators.required]
    });
  }

  onFileChanged(files: FileList) {
    this.selectedFile = files.item(0);
  }

  onChange(event) {
    if (event.checked === true) {
      this.status = 1;
    } else if (event.checked === false) {
      this.status = 2;
    }
  }

  sendParameters() {
    this.service.setImage(
      this.selectedFile,
      this.status,
      this.idEmpleado
    ).subscribe(
      res => {
        console.log(res);
        this.toastr.error('Success', '', {progressAnimation: 'decreasing', timeOut: 3000});
      },
      error => {
        console.log(error);
        this.toastr.error('Error', '', {progressAnimation: 'decreasing', timeOut: 3000});
      }
    );
  }
}

My service

setImage(image: any, status: number, idEmpleado: number): Observable<any> {
    const formData: FormData = new FormData();
    formData.append('fileKey', image.file);
    return this.http
      .post(environment.apiUrl + 'image/upload.php', formData, 
      {
        headers: new HttpHeaders()
          .set('Content-Type', 'multipart/form-data')
      }
    );
  }

This is the PHP service that receives the information and makes the saving process

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: multipart/form-data; charset=UTF-8");
header("Access-Control-Allow-Methods: PUT, GET, POST, FILES");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

$folder ="./uploads/";
$image = $_FILES['image']['name'];
$path = $folder . $image;
$target_file=$folder.basename($_FILES["image"]["name"]);
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
$allowed=array('jpeg','png' ,'jpg');


$ext=pathinfo($image, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {

    http_response_code(503);
    echo json_encode(array("message" => "Sorry, only JPG, JPEG, PNG & GIF  files are allowed."));

}

else{ 

    move_uploaded_file( $_FILES['image']['tmp_name'], $path); 
}

But I can't see where the error is in my code since I'm not receiving the image If I do tests with postman, it allows me to send the image and save it but not with Angular, unless I am not sending it correctly

Upvotes: 0

Views: 2045

Answers (2)

Mahog
Mahog

Reputation: 11

you need to remove the .file in formData and for my part, I had to remove the header in the service for it to work

Final result:

setImage(image: File, status: number, idEmpleado: number): Observable<any> {
    const formData: FormData = new FormData();
    formData.append('image', image);
    return this.http
      .post(environment.apiUrl + 'image/upload.php', formData
    );
}

Upvotes: 1

Joel Joseph
Joel Joseph

Reputation: 6169

you are appending the file as formData.append('fileKey', image.file)

So when accessing your file in your PHP code it should have been :

$image = $_FILES['fileKey']['name'];

OR just make a change in your angular code without making a change to PHP code

formData.append('image', image.file)

Upvotes: 0

Related Questions