fahad's avatar
Level 7

File Uploading Error in Vue

Hi,

i was attempting to send the file object using vue resource, In laravel dd($request) i get [] insteade of the file data. here is what i have done so far

// Markups

 <input type="file" @change="setPhoto($event)"  class="form-control file"  />

        data(){
            return{
                newSet:{
                    title: '',
                    photo: [],
                    description: '',
                    products: []
                }

            }
        },


 methods: {

            setPhoto(event){
                this.newSet.photo.push(event.target.files[0]);
            },


    createBundle(){


                this.$http.post('/admin/product-set', this.newSet).then(response => {

                   // this.resetBundle();
                   // this.setSuccess(response.data.message);

                }, response => {

                    // error

                   // this.setError(response.data);

                    console.log(response.data);

                });

            },


}

createBundle() method is finring by clicking a button, and if i use dd($request) in the controller , i get the following:

#parameters: array:4 [
      "title" => ""
      "photo" => array:1 [
        0 => []
      ]

Any help is highly appreciated.

With Thanks, Fahad

0 likes
2 replies
fahad's avatar
fahad
OP
Best Answer
Level 7

Hi, yes i have got the solutions. it requires to use new FormData() and then need to append the fields. ( sorry i should have to update this post earlier), you can try with the following code:


        data(){
            return{
                newSet:{
                    title: '',
                    price: 0,
                    photo: [],
                    description: '',
                    products: []
                }

            }
        },



methods: {

            setPhoto(event){

                this.newSet.photo = event.target.files[0];

            },

createBundle(){

                this.newSet.products = this.bundleProduct;
                this.$http.post('/admin/product-set', this.bundleData()).then(response => {
              //  this.resetBundle();
              //  this.setSuccess(response.data.message);

                }, response => {

                    // error
                 //   this.setError(response.data);

                });

            },

 bundleData(){

                var data = new FormData();
                data.append('title', this.newSet.title);
                data.append('price', this.newSet.price);
                data.append('description', this.newSet.description);
                data.append('photo' ,this.newSet.photo);
                data.append('products', JSON.stringify(this.bundleProduct));

                return data;

            },

}

Please or to participate in this conversation.