Home > Software engineering >  500 (Internal Server Error) when sending file using Axios
500 (Internal Server Error) when sending file using Axios

Time:09-22

I am trying to send file using Axios in Laravel and Vuejs. All the data stored in variantsProd variable below:

data() {
    return {
        form: new Form({
            variantsProd: [],
        }),
        
    };
},

The variantsProd contains below data: enter image description here

The problem is in images attribute. It's contain a file. If I change a value of images with [] it's working, all data can be sent. But if I attach an image/s, I always get 500 (Internal Server Error). I have no idea why does this happens?

let formData = new FormData();
        let varProd = JSON.stringify(this.form.variantsProd);
        formData.append('variantsProd', varProd);

        this.form
            .post('api/staff/products/store', formData, {
                header: {
                    'Content-Type': 'multipart/form-data',
                },
            })
            .then((response) => {
                console.log(response);
                if (this.form.isVariantExists > 0) {
                    this.validateVariants(response);
                } else {
                    this.$router.push({ name: 'products-index' });
                    this.showSuccessMsg(response);
                }
            })
            .catch((error) => {
                console.log(error);
                swal.fire({
                    icon: 'error',
                    title: 'Oouch...',
                    text: 'Something went wrong! Make sure you input the valid data!',
                    footer: '<a href>Why do I have this issue?</a>',
                });
            })
            .finally(() => {
                $('#loadingButton').attr('disabled', false);
                $('.proc-regis').remove();
                $('#loadingButton').html(`Save`);
            });

[UPDATE] And this is how I save the file in variantsProd before I send it through axios.

this.form.variantsProd.forEach((item) => {
            let totalImages = $('.images'   item.id)[0].files.length; 
            let images = $('.images'   item.id)[0];
            let getImg = [];
            for (let i = 0; i < totalImages; i  ) {
                getImg.push(images.files[i]);
            }

            item.total_images = totalImages;
            item.images = getImg; // error here, cant sent this data to controller

        });

FYI: I am using bootstrap-fileinput in this case.

CodePudding user response:

Error 500 means that the server doesn't know how to process your request. Make sure your request matches the format the server expects.

CodePudding user response:

 <input type="file" ref="identity_card" />
 let identity_card = this.$refs.identity_card.files[0];
 form.append("identity_card_image", identity_card);
       axios.post(`api_url`, form)
         .then(response => {
       })

You can try it.

  • Related