0

the following script will show, how I run an AJAX call to send some files(Images) to the server. But if I show the values in the $_POST in PHP, I recieve an empty array.

upload():void {

        let headers = new Headers();
        let formData: FormData = new FormData();

        for(let i = 0; i < this.files.length; i++){
            formData.append(i.toString(), this.files[i], this.files[i].name);
        }

//next line is updated
       formData.append('x', "test");

        var returnReponse = new Promise((resolve, reject) => {
            this.http.post('save.php', formData, {
                headers: headers
            }).subscribe(
                res => {
                    console.info(res);
                },
                error => {
                    console.info(error);
                }
            );
        });

I receive the PHPoutput with FirePHP and FireBug, so the call reach the server. Where is my mistake that the $_POST variable still empty?

michael-mammut
  • 2,595
  • 5
  • 28
  • 46
  • I can be wrong but it seems like you don't set your headers properly. Maybe this could help :`headers = new Headers({'Content-Type': 'application/json'});` – mickdev Jan 27 '17 at 08:38
  • @mickdev Thank you for your fast response, i added the `header` to the `post` but it also did not work. a little bit strage to me is, if I add this code `formData.append('x', "test"); ` below the for-loop, I receive the `$_POST['x']` variable with their value, but not the appended files from the for loo. – michael-mammut Jan 27 '17 at 08:48
  • can you show us how your `formData` looks like ? Because, you can send your file like this : `formData.append("youfile", fileInputElement.files[0]);` – mickdev Jan 27 '17 at 08:53
  • Now I'm totaly confuse... formData is empty, but ... i reach the `x` on the server. How can i reach this? if he formData is emtpy? – michael-mammut Jan 27 '17 at 09:00
  • @mickdev well.. the post to the server is reachable. The output of `$_FILE` contains the correct variable. But, the `size` and `tmp_name`is empty. Is there something to set ? I try to find out something about, but without success.. – michael-mammut Jan 27 '17 at 10:15
  • Did you serialize your FormData ? Serializing a file give an empty array {}. Take a look at [this function about AngularJs file upload](http://stackoverflow.com/questions/37039852/send-formdata-with-other-field-in-angular). Maybe you can adapt it to Angular 2. – mickdev Jan 27 '17 at 19:54

0 Answers0