Axios/Ajax HTTP patch requests with file not working

Published 1 year ago by rickbolton

I'm using Axios HTTP requests however, I've also tried using jQuery ajax and getting the same result


let files = e.target.files || e.dataTransfer.files;
                if (!files.length) {
                    return;
                }

                let form = new FormData();
                form.append('profile_picture', files[0]);

                axios.patch('/profile', form)
                .then((response) => {
                    console.log(response);
                });

                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });

                $.ajax({
                    url: '/profile',
                    type: 'patch',
                    data: form,
                    cache: false,
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        console.log(response);
                    }
               });
                    

When it's a PATCH request the file does not appear in the request in Laravel. However, when I change it to POST the file appears correctly. Has anyone come across this and have a way to get this working using PATCH request? Or is it fine to use POST even though I'm updating a record?

Thanks!

Best Answer (As Selected By rickbolton)
rickbolton

For the time being I've used POST and added _method to the FormData

form.append('_method', 'PATCH');

If anyone has a better solution to this then that would be appreciated. Thanks!

rickbolton

For the time being I've used POST and added _method to the FormData

form.append('_method', 'PATCH');

If anyone has a better solution to this then that would be appreciated. Thanks!

ejdelmonico

Are you properly spoofing the form method? Here is why https://laravel.com/docs/5.3/routing#form-method-spoofing

Corben

I just ran into the same issue.

When trying to send form data with axios.patch, the request looks the same as when sending with axios.post and having the hidden field _method = patch somewhere (I'm using {{ method_field('PATCH') }} in my inline template). In both situations I end up correctly in the update() method of my controller. With the difference that when I send with axios.patch the request() data is empty.

Using axios.post I can get the form data via the request() method.

I couldn't find any informations on this so far, so I wondering if this is intended behaviour and how the data should be structured to use axios.patch with FormData. From the Let's Build A Forum with Laravel and TDD series we know it's possible to use axios.patch, with the data is not being a FormData object, but a javascript object.

Please sign in or create an account to participate in this conversation.