0

I want to upload a pdf file with angular and with php api. I have been trying to make the solution proposed here ( File Upload In Angular?) work with php api.

I tested the code but it doesn't work.

this is the code in html file

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">

Here is the ts code, i changed it a little bit, from the code in the URL that i put above, to make it work with HttpClient

  fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        let headers = new HttpHeaders();
        /** In Angular 5, including the header Content-Type can invalidate your request */
         headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
      //  let options = new RequestOptions({ headers: headers });
        const options = {
          params: new HttpParams(),
          headers:  headers
        };
        this.Http.post(`http://localhost/Back/ajouterPublication.php`, formData, options)

            .subscribe(
                data => console.log('success'),
                error => console.log(error)
            )
    }
}

and here is the php api

<?php

header("Access-Control-Allow-Origin: *");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  echo json_encode(array('status' => false));
  exit;
}

$path = 'http://localhost//fichier';

if (isset($_FILES['file'])) { 
  $generatedName ='abc.pdf';
  $filePath = $path.$generatedName;

  if (!is_writable($path)) {
    echo json_encode(array(
      'status' => false,
      'msg'    => 'Destination directory not writable.'
    ));
    exit;
  }

  if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
    echo json_encode(array(
      'status'        => true,
      'originalName'  => $originalName,
      'generatedName' => $generatedName
    ));
  }
}
else {
  echo json_encode(
    array('status' => false, 'msg' => 'No file uploaded.')
  );
  exit;
}

?>

I'm using angular 7.2.1

CodIn
  • 29
  • 8

1 Answers1

0

Your API request parameter is uploadFile and you are using the file.

Replace this within your PHP File.

<?php

header("Access-Control-Allow-Origin: *");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  echo json_encode(array('status' => false));
  exit;
}

$path=$_SERVER['DOCUMENT_ROOT'] . "/your folder name/";

if (isset($_FILES['uploadFile'])) { 
  $generatedName ='abc.pdf';
  $filePath = $path.$generatedName;

  if (!is_writable($path)) {
    echo json_encode(array(
      'status' => false,
      'msg'    => 'Destination directory not writable.'
    ));
    exit;
  }

  if (move_uploaded_file($_FILES['uploadFile']['tmp_name'], $filePath)) {
    echo json_encode(array(
      'status'        => true,
      'originalName'  => $originalName,
      'generatedName' => $generatedName
    ));
  }
}
else {
  echo json_encode(
    array('status' => false, 'msg' => 'No file uploaded.')
  );
  exit;
}

?>
Shubham Azad
  • 786
  • 2
  • 10
  • 25
  • Thank you for your response. I tried it, but it is still not working. – CodIn Feb 14 '19 at 05:22
  • I don't think so it is the relation of wamp here . – Shubham Azad Feb 14 '19 at 08:31
  • you can use $path=$_SERVER['DOCUMENT_ROOT'] . "/your folder name/"; – Shubham Azad Feb 14 '19 at 08:33
  • In the console of the browser i get : HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost/Back/ajouterPublication.php", ok: false, …} SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () .... {"status":true,"originalName":null,"generatedName":"abc.pdf"}" ... so i verified the api and i found that i'm using the variable 'originalName' => $originalName, without declaring it first. Thank you for your help @Shubham – CodIn Feb 14 '19 at 08:45
  • Also , i changed the path to C:\wamp\www\fichier – CodIn Feb 14 '19 at 08:46
  • welcome CodIn.if you got the solution then upvote my answer. – Shubham Azad Feb 14 '19 at 09:16