GodziLaravel's avatar

I Can't receive file from axios patch method

Hello , I try to upload a file :

 <input v-on:change="onImageChange" type="file" class="custom-file-input" :id="'customFile'+id">
(...)
        updateCompany(id) {
            axios.post('/api/companies/' + id, {
                _method: 'patch',
                company: this.companyData,
                imageAvatar:this.imageAvatar
            }).then((response) => {
                this.$refs.closeModal.click();
                this.companyUpdatedConfirmation();
            })
        },
        onImageChange(e) {
                console.log(e.target.files[0]);
                this.imageAvatar = e.target.files[0];
                console.log(this.imageAvatar);
        }

But, in update controller the result is always empty and when I :

dd($request->hasFile('imageAvatar')); it returns false !

Any suggestion ?

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

If you want to sent files in an XHR request, then you must setup a FormData object:

updateCompany(id) {
	let form = new FormData();
  	Object.keys(this.form).forEach((key) => {
    	form.append(key, this.form[key])
  	})
	form.append('imageAvatar', this.imageAvatar);
	axios({
    	method: 'patch',
    	url: '/api/companies/' + id,
    	data: form
    })..then((response) => {
		this.$refs.closeModal.click();
		this.companyUpdatedConfirmation();
})
GodziLaravel's avatar

@tykus thanks :

I modified some stuff and this works :

let form = new FormData();
            Object.keys(this.companyData).forEach((key) => {
                form.append(key, this.companyData[key])
            });
            form.append('companiesLogos', this.companiesLogos);
            form.append('_method', 'patch');
            axios.post('/api/companies/' + id, form)
                .then((response) => {
                this.$refs.closeModal.click();
                this.companyUpdatedConfirmation();
            }).catch((error)=> {
                console.log(error.response.data)
            })

Please or to participate in this conversation.