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 !

7
  • Have you tried making the POST request with multipart/form-data content type? Commented Oct 2, 2020 at 20:59
  • Yes. I already did too, but still $ FILES is still empty Commented Oct 2, 2020 at 21:03
  • Hmm, what structure does your php://input show? Commented Oct 2, 2020 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 Commented Oct 2, 2020 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: stackoverflow.com/questions/40351429/… Commented Oct 2, 2020 at 21:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.