Send and receive file Vue-Resource and PHP

0

I'm trying to send an image using vue-resource and retrieve it in a php file but I have not succeeded, this is my JS file:

//* AJAX *//
startAsyncNews: function(){
    if(this.sendimage){
        var formdata = new FormData();
        formdata.append("file",this.contentnew.imageFile );
        console.log(this.contentnew.imageFile);
    }   

    // POST /someUrl
    this.$http.post('controllers/newsController.php', { 
        data:{action : this.accion_new, data_new: this.contentnew , imgf : formdata}
    }).then(response => {
    }, response => {
        console.log("error");
    });
},
imageSelect: function($event){
    this.sendimage=true;
    this.contentnew.imageFile =$event.target.files[0];  
}

When I use the console.log = console.log(this.contentnew.imageFile); it shows me the properties of the image correctly, that is to say it is sending the file well, but when I receive it in php and I do vardump I get like this object(stdclass)#3 (0) no properties no properties and with json_decode / encode me it is empty, also try without

headers: {
    'content-type': 'multipart/form-data'
}

But it generates the following error:

  

Missing boundary in multipart / form-data POST

    
asked by Andress Blend 13.08.2018 в 22:44
source

1 answer

0

You can try this way:

this.$http.post('controllers/newsController.php', data, {
   emulateJSON: true
})

That code will send the request as application / x-www-form-urlencoded.

Or you can use a FormData:

var formData = new FormData();
formData.append('action', this.action);
formData.append('data_new', this.contentnew)
formData.append('imgf', this.contentnew.imageFile);

this.$http.post('controllers/newsController.php', formData).then(response => {
    // success callback
  }, response => {
    // error callback
  });

Try to send all the parameters in the formdata not only the file, as in the example I put above, and send the post only the formdata.

To access the file via php you must do the following:

$_FILES['imgf'];

If you write:

var_dump($_FILES['imgf']);

It should show you something like this:

array(5) { ["name"]=> string(31) "serverless-square-icon-text.png" ["type"]=> string(9) "image/png" ["tmp_name"]=> string(25) "/opt/lampp/temp/phpO680V7" ["error"]=> int(0) ["size"]=> int(70686) }
    
answered by 14.08.2018 в 07:48