I’m trying to upload a file to a php server through an http request in angular 9, but the server is not able to receive the uploaded file in $_FILES. The code which I wrote somewhat looks like:
html:
<input type="file" (change)="detectFiles($event)" name="testFile" >
php:
<?php
    header("Access-Control-Allow-Origin: *"); 
    header('Access-Control-Allow-Credentials: true');
    header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    echo json_encode($_FILES['testFile']['name']);
?>
typescript:
detectFiles(event) {
   const file = event.target.files[0];
   this.httpClient.post<any>('http://localhost/test/uploadFile.php', file )
     .subscribe( (response) => { console.log('uploading is done: ' + response); },
                 (error) => { console.log('ERR during the uploading: ' + error); }  
   );
}
when I upload a file I’m having as result the following message: ERR during the uploading: [object Object]. Is there any possibility to reach the uploaded file from $_FILES in the server side? Thanks in advance.
Advertisement
Answer
append your file into Formdata and send this
detectFiles(event) {
   var formData = new FormData();
   formData.append("file", event.target.files[0]);  
   this.httpClient.post<any>('http://localhost/test/uploadFile.php', formData)
     .subscribe( (response) => { console.log('uploading is done: ' + response); },
                 (error) => { console.log('ERR during the uploading: ' + error); }  
   );
}