2

I'm uploading images with formdata and axios. I'm using symfony for my back end and I need to access my image file and other parameter both. This is my axios code.

axios.post(testUp, { data: formData, ad: 12 }, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(response => {

                });

And here is my symfony code.

/**
 * @Route("/test_up", name="test_up", methods={"GET","POST"})
 */
public function testUp(Request $request, CarRepository $carRepository) {
    dd($request->files->all());
}

Unfortunately I'm getting null as output. I'm getting the formdata from image uploaded and it's a formdata object. It works if I do this but need both parameters.

axios.post(testUp, formData, {
                 headers: {
                     'Content-Type': 'multipart/form-data'
                 }
             }).then(response => {
                 alert('*');
                 console.log(response);
             });

but I need to send other parameter too.

vimuth
  • 5,064
  • 33
  • 79
  • 116

2 Answers2

2

You cant mix FormData with JSON. It is related question

Send FormData object AND an additional parameter via ajax

If you have only one parameter - ad = 12 I recommend to use code:

axios.post(testUp + "?" + (new URLSearchParams({ad: 12})).toString()
, formData, {
                 headers: {
                     'Content-Type': 'multipart/form-data'
                 }
             }).then(response => {
                 alert('*');
                 console.log(response);
             });
Daniel
  • 7,684
  • 7
  • 52
  • 76
1

On Symfony side you should use a form so you can receive many type of data. See documentation here: https://symfony.com/doc/current/forms.html

On vuejs/axios side, you just cant send json content AND form data content at the same time (as it is 2 different type of data). But you can add some content to your form data (just like you can have a file with other fields in your Symfony form).

Nek
  • 2,715
  • 1
  • 20
  • 34