0

I'm using FormData to send a file from ionic with angular to PHP, but in the PHP backend when you make var dump $_FILES appear empty.

This is my code in .ts:

  file: File;
  changeListener($event): void {
    this.file = $event.target.files[0];
    console.info(this.file); //First console info
    const formData = new FormData();
    const blobFile = new Blob([this.file], { type: this.file.type });

    formData.append("file", blobFile, "filename");
 
    this.myService.testing(formData).subscribe( resp => {
        
      },(error)=>{
       
        console.info(error);
        
        
      })  

  }

In the service:

testing(data) {

return this.http.post(url, body, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})

}

The PHP Backed :

$postdata = file_get_contents("php://input"); // this shows me the contents of the file
var_dump($_FILES); // returns an empty array

So, what's my mistake? Am I sending badly from Ionic or am I getting bad in PHP ?

I'm using codeigniter 3

Thanks !

  • Have you tried making the POST request with `multipart/form-data` content type? – ΔO 'delta zero' Oct 02 '20 at 20:59
  • Yes. I already did too, but still $ FILES is still empty – Oscar Galvis Oct 02 '20 at 21:03
  • Hmm, what structure does your `php://input` show? – ΔO 'delta zero' Oct 02 '20 at 21:06
  • $postdata = file_get_contents("php://input"); var_dump($postdata); Shows me the contents of the file (txt) but I need to upload the file to a folder – Oscar Galvis Oct 02 '20 at 21:18
  • Try calling the post() like this (without header information): `this.http.post(url, body)`. The browser will set the multipart/form-data automatically and will define the `boundary` as well. Just setting the header multipar/form-data and not setting the boundary will not work. See this for more info about boundary: https://stackoverflow.com/questions/40351429/formdata-how-to-get-or-set-boundary-in-multipart-form-data-angular – francisco neto Oct 02 '20 at 21:20
  • @francisco neto is correct!. I deleted the header and now if it works. thank you very much – Oscar Galvis Oct 02 '20 at 21:41
  • Does this answer your question? [FormData how to get or set boundary in multipart/form-data - Angular](https://stackoverflow.com/questions/40351429/formdata-how-to-get-or-set-boundary-in-multipart-form-data-angular) – francisco neto Oct 02 '20 at 23:06

0 Answers0