How to upload image from VueJS to Symfony with Axios?












0















I have the VueJS component installed without problem in my project with Symfony 4 but at the moment I want to upload an image. I follow this reference from Laravel: How to upload image from VueJS to Laravel with Axios?



I get to the controller but that's where the value in base 64 does not reach just the console message.



Code:



//CargaFoto.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<input type="file" name="image" @change="getImage" accept="image/*">
<button @click="updateAvatar">Subir Imagen</button>
</div>
</div>
</template>

<script>
import axios from 'axios'

export default {
name: "CargaFoto",
data() {
return {
msg: "Cargar Imagen de Perfil",
imagen: null
};
},
methods: {
getImage(event){
//Asignamos la imagen a nuestra data
this.imagen = event.target.files[0];
},
updateAvatar(){
//Creamos el formData
var data = new FormData();
data.append('avatar', this.imagen);
data.append('_method', 'POST');
//Enviamos la petición
axios.post('/usuario/jsonimagen',data)
.then(response => {
console.log(res)
})
}
</script>


And this the controller code:



/**
* @return JsonResponse
* @Route("/jsonimagen", name="jsonimagen", methods="POST")
*/
public function jsonimagen(Request $request):JsonResponse
{

$data= $request->get("data");
return $this->json($data);
}


The answer is null The doubt that I have is how I upload the image to the local server.










share|improve this question



























    0















    I have the VueJS component installed without problem in my project with Symfony 4 but at the moment I want to upload an image. I follow this reference from Laravel: How to upload image from VueJS to Laravel with Axios?



    I get to the controller but that's where the value in base 64 does not reach just the console message.



    Code:



    //CargaFoto.vue
    <template>
    <div class="hello">
    <h1>{{ msg }}</h1>
    <input type="file" name="image" @change="getImage" accept="image/*">
    <button @click="updateAvatar">Subir Imagen</button>
    </div>
    </div>
    </template>

    <script>
    import axios from 'axios'

    export default {
    name: "CargaFoto",
    data() {
    return {
    msg: "Cargar Imagen de Perfil",
    imagen: null
    };
    },
    methods: {
    getImage(event){
    //Asignamos la imagen a nuestra data
    this.imagen = event.target.files[0];
    },
    updateAvatar(){
    //Creamos el formData
    var data = new FormData();
    data.append('avatar', this.imagen);
    data.append('_method', 'POST');
    //Enviamos la petición
    axios.post('/usuario/jsonimagen',data)
    .then(response => {
    console.log(res)
    })
    }
    </script>


    And this the controller code:



    /**
    * @return JsonResponse
    * @Route("/jsonimagen", name="jsonimagen", methods="POST")
    */
    public function jsonimagen(Request $request):JsonResponse
    {

    $data= $request->get("data");
    return $this->json($data);
    }


    The answer is null The doubt that I have is how I upload the image to the local server.










    share|improve this question

























      0












      0








      0


      1






      I have the VueJS component installed without problem in my project with Symfony 4 but at the moment I want to upload an image. I follow this reference from Laravel: How to upload image from VueJS to Laravel with Axios?



      I get to the controller but that's where the value in base 64 does not reach just the console message.



      Code:



      //CargaFoto.vue
      <template>
      <div class="hello">
      <h1>{{ msg }}</h1>
      <input type="file" name="image" @change="getImage" accept="image/*">
      <button @click="updateAvatar">Subir Imagen</button>
      </div>
      </div>
      </template>

      <script>
      import axios from 'axios'

      export default {
      name: "CargaFoto",
      data() {
      return {
      msg: "Cargar Imagen de Perfil",
      imagen: null
      };
      },
      methods: {
      getImage(event){
      //Asignamos la imagen a nuestra data
      this.imagen = event.target.files[0];
      },
      updateAvatar(){
      //Creamos el formData
      var data = new FormData();
      data.append('avatar', this.imagen);
      data.append('_method', 'POST');
      //Enviamos la petición
      axios.post('/usuario/jsonimagen',data)
      .then(response => {
      console.log(res)
      })
      }
      </script>


      And this the controller code:



      /**
      * @return JsonResponse
      * @Route("/jsonimagen", name="jsonimagen", methods="POST")
      */
      public function jsonimagen(Request $request):JsonResponse
      {

      $data= $request->get("data");
      return $this->json($data);
      }


      The answer is null The doubt that I have is how I upload the image to the local server.










      share|improve this question














      I have the VueJS component installed without problem in my project with Symfony 4 but at the moment I want to upload an image. I follow this reference from Laravel: How to upload image from VueJS to Laravel with Axios?



      I get to the controller but that's where the value in base 64 does not reach just the console message.



      Code:



      //CargaFoto.vue
      <template>
      <div class="hello">
      <h1>{{ msg }}</h1>
      <input type="file" name="image" @change="getImage" accept="image/*">
      <button @click="updateAvatar">Subir Imagen</button>
      </div>
      </div>
      </template>

      <script>
      import axios from 'axios'

      export default {
      name: "CargaFoto",
      data() {
      return {
      msg: "Cargar Imagen de Perfil",
      imagen: null
      };
      },
      methods: {
      getImage(event){
      //Asignamos la imagen a nuestra data
      this.imagen = event.target.files[0];
      },
      updateAvatar(){
      //Creamos el formData
      var data = new FormData();
      data.append('avatar', this.imagen);
      data.append('_method', 'POST');
      //Enviamos la petición
      axios.post('/usuario/jsonimagen',data)
      .then(response => {
      console.log(res)
      })
      }
      </script>


      And this the controller code:



      /**
      * @return JsonResponse
      * @Route("/jsonimagen", name="jsonimagen", methods="POST")
      */
      public function jsonimagen(Request $request):JsonResponse
      {

      $data= $request->get("data");
      return $this->json($data);
      }


      The answer is null The doubt that I have is how I upload the image to the local server.







      php symfony vue.js axios






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 28 '18 at 16:38









      juanitourquizajuanitourquiza

      389518




      389518
























          2 Answers
          2






          active

          oldest

          votes


















          0














          You're sending file content as avatar variable, why do you try to get request's data then?



          Correct form would be:



          $avatar = $request->file('avatar');


          Also, you can omit adding _method: 'POST' to sent data as you're doing axios.post already.






          share|improve this answer
























          • Hi, thanks for your answer but the error continues, the result is null: "Attempted to call an undefined method named "file" of class "SymfonyComponentHttpFoundationRequest"."

            – juanitourquiza
            Jan 1 at 1:03











          • @juanitourquiza, you Request should be IlluminateHttpRequest

            – Styx
            Jan 2 at 5:19











          • Have a look here: laravel.com/docs/5.7/requests#retrieving-uploaded-files

            – Styx
            Jan 2 at 5:20











          • thank you for your answer but I am using symfony not laravel. I already collect the data but I have them in the temporary folder

            – juanitourquiza
            Jan 2 at 9:20











          • You got me confused, I thought you were using Laravel.

            – Styx
            Jan 2 at 21:48



















          0














          Based on the link of a comment indicated by Fran I could see that the header was missing and then collect the data in Symfony in the same route that was already defined.



          The template file was like this:



          //CargaFoto.vue
          <template>
          <div class="hello">
          <h1>{{ msg }}</h1>
          <div class="container">
          <div class="large-12 medium-12 small-12 cell">
          <label>File
          <input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
          </label>
          <button v-on:click="submitFile()">Submit</button>
          </div>
          </div>

          </div>
          </div>
          </template>

          <script>
          import axios from 'axios'

          export default {
          name: "CargaFoto",
          data() {
          return {
          msg: "Cargar Imagen de Perfil",
          file: ''
          //selectedFile: null
          };
          },
          methods: {
          submitFile(){
          /*
          Initialize the form data
          */
          let formData = new FormData();

          /*
          Add the form data we need to submit
          */
          formData.append('file', this.file);

          /*
          Make the request to the POST /single-file URL
          */
          axios.post( '/usuario/jsonimagen',
          formData,
          {
          headers: {
          'Content-Type': 'multipart/form-data'
          }
          }
          ).then(function(){
          console.log('SUCCESS!!');
          })
          .catch(function(){
          console.log('FAILURE!!');
          });
          },

          /*
          Handles a change on the file upload
          */
          handleFileUpload(){
          this.file = this.$refs.file.files[0];
          }
          }
          };
          </script>

          <!-- Add "scoped" attribute to limit CSS to this component only -->
          <style>
          #fileInput {
          display: none;
          }
          h1,
          h2 {
          font-weight: normal;
          }
          ul {
          list-style-type: none;
          padding: 0;
          }
          li {
          display: inline-block;
          margin: 0 10px;
          }
          a {
          color: #42b983;
          }
          .my-8 {
          margin-top: 4rem;
          margin-bottom: 4rem;
          }
          </style>


          In the file where the data is request, the controller is:



          //src/UsuarioController.php
          /**
          * @return JsonResponse
          * @Route("/jsonimagen", name="jsonimagen", methods="POST")

          */
          public function jsonimagen(Request $request):JsonResponse
          {
          $usuario = $this->getUser();
          $data = $request->files->get('file');
          $fileName = $usuario.'.'.$data->guessExtension();
          // moves the file to the directory where usuarios are stored
          $data->move(
          $this->getParameter('usuarios_directorio'),
          $fileName
          );
          echo $data; exit;
          return $this->json($data);
          }


          Also configure the path where the images will be loaded in the file



          //services.yaml
          parameters:
          locale: 'en'
          usuarios_directorio: '%kernel.project_dir%/public/uploads/usuarios'


          Here you can see the image loaded in this capture.



          enter image description here






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53961605%2fhow-to-upload-image-from-vuejs-to-symfony-with-axios%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            You're sending file content as avatar variable, why do you try to get request's data then?



            Correct form would be:



            $avatar = $request->file('avatar');


            Also, you can omit adding _method: 'POST' to sent data as you're doing axios.post already.






            share|improve this answer
























            • Hi, thanks for your answer but the error continues, the result is null: "Attempted to call an undefined method named "file" of class "SymfonyComponentHttpFoundationRequest"."

              – juanitourquiza
              Jan 1 at 1:03











            • @juanitourquiza, you Request should be IlluminateHttpRequest

              – Styx
              Jan 2 at 5:19











            • Have a look here: laravel.com/docs/5.7/requests#retrieving-uploaded-files

              – Styx
              Jan 2 at 5:20











            • thank you for your answer but I am using symfony not laravel. I already collect the data but I have them in the temporary folder

              – juanitourquiza
              Jan 2 at 9:20











            • You got me confused, I thought you were using Laravel.

              – Styx
              Jan 2 at 21:48
















            0














            You're sending file content as avatar variable, why do you try to get request's data then?



            Correct form would be:



            $avatar = $request->file('avatar');


            Also, you can omit adding _method: 'POST' to sent data as you're doing axios.post already.






            share|improve this answer
























            • Hi, thanks for your answer but the error continues, the result is null: "Attempted to call an undefined method named "file" of class "SymfonyComponentHttpFoundationRequest"."

              – juanitourquiza
              Jan 1 at 1:03











            • @juanitourquiza, you Request should be IlluminateHttpRequest

              – Styx
              Jan 2 at 5:19











            • Have a look here: laravel.com/docs/5.7/requests#retrieving-uploaded-files

              – Styx
              Jan 2 at 5:20











            • thank you for your answer but I am using symfony not laravel. I already collect the data but I have them in the temporary folder

              – juanitourquiza
              Jan 2 at 9:20











            • You got me confused, I thought you were using Laravel.

              – Styx
              Jan 2 at 21:48














            0












            0








            0







            You're sending file content as avatar variable, why do you try to get request's data then?



            Correct form would be:



            $avatar = $request->file('avatar');


            Also, you can omit adding _method: 'POST' to sent data as you're doing axios.post already.






            share|improve this answer













            You're sending file content as avatar variable, why do you try to get request's data then?



            Correct form would be:



            $avatar = $request->file('avatar');


            Also, you can omit adding _method: 'POST' to sent data as you're doing axios.post already.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 28 '18 at 16:49









            StyxStyx

            3,39142434




            3,39142434













            • Hi, thanks for your answer but the error continues, the result is null: "Attempted to call an undefined method named "file" of class "SymfonyComponentHttpFoundationRequest"."

              – juanitourquiza
              Jan 1 at 1:03











            • @juanitourquiza, you Request should be IlluminateHttpRequest

              – Styx
              Jan 2 at 5:19











            • Have a look here: laravel.com/docs/5.7/requests#retrieving-uploaded-files

              – Styx
              Jan 2 at 5:20











            • thank you for your answer but I am using symfony not laravel. I already collect the data but I have them in the temporary folder

              – juanitourquiza
              Jan 2 at 9:20











            • You got me confused, I thought you were using Laravel.

              – Styx
              Jan 2 at 21:48



















            • Hi, thanks for your answer but the error continues, the result is null: "Attempted to call an undefined method named "file" of class "SymfonyComponentHttpFoundationRequest"."

              – juanitourquiza
              Jan 1 at 1:03











            • @juanitourquiza, you Request should be IlluminateHttpRequest

              – Styx
              Jan 2 at 5:19











            • Have a look here: laravel.com/docs/5.7/requests#retrieving-uploaded-files

              – Styx
              Jan 2 at 5:20











            • thank you for your answer but I am using symfony not laravel. I already collect the data but I have them in the temporary folder

              – juanitourquiza
              Jan 2 at 9:20











            • You got me confused, I thought you were using Laravel.

              – Styx
              Jan 2 at 21:48

















            Hi, thanks for your answer but the error continues, the result is null: "Attempted to call an undefined method named "file" of class "SymfonyComponentHttpFoundationRequest"."

            – juanitourquiza
            Jan 1 at 1:03





            Hi, thanks for your answer but the error continues, the result is null: "Attempted to call an undefined method named "file" of class "SymfonyComponentHttpFoundationRequest"."

            – juanitourquiza
            Jan 1 at 1:03













            @juanitourquiza, you Request should be IlluminateHttpRequest

            – Styx
            Jan 2 at 5:19





            @juanitourquiza, you Request should be IlluminateHttpRequest

            – Styx
            Jan 2 at 5:19













            Have a look here: laravel.com/docs/5.7/requests#retrieving-uploaded-files

            – Styx
            Jan 2 at 5:20





            Have a look here: laravel.com/docs/5.7/requests#retrieving-uploaded-files

            – Styx
            Jan 2 at 5:20













            thank you for your answer but I am using symfony not laravel. I already collect the data but I have them in the temporary folder

            – juanitourquiza
            Jan 2 at 9:20





            thank you for your answer but I am using symfony not laravel. I already collect the data but I have them in the temporary folder

            – juanitourquiza
            Jan 2 at 9:20













            You got me confused, I thought you were using Laravel.

            – Styx
            Jan 2 at 21:48





            You got me confused, I thought you were using Laravel.

            – Styx
            Jan 2 at 21:48













            0














            Based on the link of a comment indicated by Fran I could see that the header was missing and then collect the data in Symfony in the same route that was already defined.



            The template file was like this:



            //CargaFoto.vue
            <template>
            <div class="hello">
            <h1>{{ msg }}</h1>
            <div class="container">
            <div class="large-12 medium-12 small-12 cell">
            <label>File
            <input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
            </label>
            <button v-on:click="submitFile()">Submit</button>
            </div>
            </div>

            </div>
            </div>
            </template>

            <script>
            import axios from 'axios'

            export default {
            name: "CargaFoto",
            data() {
            return {
            msg: "Cargar Imagen de Perfil",
            file: ''
            //selectedFile: null
            };
            },
            methods: {
            submitFile(){
            /*
            Initialize the form data
            */
            let formData = new FormData();

            /*
            Add the form data we need to submit
            */
            formData.append('file', this.file);

            /*
            Make the request to the POST /single-file URL
            */
            axios.post( '/usuario/jsonimagen',
            formData,
            {
            headers: {
            'Content-Type': 'multipart/form-data'
            }
            }
            ).then(function(){
            console.log('SUCCESS!!');
            })
            .catch(function(){
            console.log('FAILURE!!');
            });
            },

            /*
            Handles a change on the file upload
            */
            handleFileUpload(){
            this.file = this.$refs.file.files[0];
            }
            }
            };
            </script>

            <!-- Add "scoped" attribute to limit CSS to this component only -->
            <style>
            #fileInput {
            display: none;
            }
            h1,
            h2 {
            font-weight: normal;
            }
            ul {
            list-style-type: none;
            padding: 0;
            }
            li {
            display: inline-block;
            margin: 0 10px;
            }
            a {
            color: #42b983;
            }
            .my-8 {
            margin-top: 4rem;
            margin-bottom: 4rem;
            }
            </style>


            In the file where the data is request, the controller is:



            //src/UsuarioController.php
            /**
            * @return JsonResponse
            * @Route("/jsonimagen", name="jsonimagen", methods="POST")

            */
            public function jsonimagen(Request $request):JsonResponse
            {
            $usuario = $this->getUser();
            $data = $request->files->get('file');
            $fileName = $usuario.'.'.$data->guessExtension();
            // moves the file to the directory where usuarios are stored
            $data->move(
            $this->getParameter('usuarios_directorio'),
            $fileName
            );
            echo $data; exit;
            return $this->json($data);
            }


            Also configure the path where the images will be loaded in the file



            //services.yaml
            parameters:
            locale: 'en'
            usuarios_directorio: '%kernel.project_dir%/public/uploads/usuarios'


            Here you can see the image loaded in this capture.



            enter image description here






            share|improve this answer




























              0














              Based on the link of a comment indicated by Fran I could see that the header was missing and then collect the data in Symfony in the same route that was already defined.



              The template file was like this:



              //CargaFoto.vue
              <template>
              <div class="hello">
              <h1>{{ msg }}</h1>
              <div class="container">
              <div class="large-12 medium-12 small-12 cell">
              <label>File
              <input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
              </label>
              <button v-on:click="submitFile()">Submit</button>
              </div>
              </div>

              </div>
              </div>
              </template>

              <script>
              import axios from 'axios'

              export default {
              name: "CargaFoto",
              data() {
              return {
              msg: "Cargar Imagen de Perfil",
              file: ''
              //selectedFile: null
              };
              },
              methods: {
              submitFile(){
              /*
              Initialize the form data
              */
              let formData = new FormData();

              /*
              Add the form data we need to submit
              */
              formData.append('file', this.file);

              /*
              Make the request to the POST /single-file URL
              */
              axios.post( '/usuario/jsonimagen',
              formData,
              {
              headers: {
              'Content-Type': 'multipart/form-data'
              }
              }
              ).then(function(){
              console.log('SUCCESS!!');
              })
              .catch(function(){
              console.log('FAILURE!!');
              });
              },

              /*
              Handles a change on the file upload
              */
              handleFileUpload(){
              this.file = this.$refs.file.files[0];
              }
              }
              };
              </script>

              <!-- Add "scoped" attribute to limit CSS to this component only -->
              <style>
              #fileInput {
              display: none;
              }
              h1,
              h2 {
              font-weight: normal;
              }
              ul {
              list-style-type: none;
              padding: 0;
              }
              li {
              display: inline-block;
              margin: 0 10px;
              }
              a {
              color: #42b983;
              }
              .my-8 {
              margin-top: 4rem;
              margin-bottom: 4rem;
              }
              </style>


              In the file where the data is request, the controller is:



              //src/UsuarioController.php
              /**
              * @return JsonResponse
              * @Route("/jsonimagen", name="jsonimagen", methods="POST")

              */
              public function jsonimagen(Request $request):JsonResponse
              {
              $usuario = $this->getUser();
              $data = $request->files->get('file');
              $fileName = $usuario.'.'.$data->guessExtension();
              // moves the file to the directory where usuarios are stored
              $data->move(
              $this->getParameter('usuarios_directorio'),
              $fileName
              );
              echo $data; exit;
              return $this->json($data);
              }


              Also configure the path where the images will be loaded in the file



              //services.yaml
              parameters:
              locale: 'en'
              usuarios_directorio: '%kernel.project_dir%/public/uploads/usuarios'


              Here you can see the image loaded in this capture.



              enter image description here






              share|improve this answer


























                0












                0








                0







                Based on the link of a comment indicated by Fran I could see that the header was missing and then collect the data in Symfony in the same route that was already defined.



                The template file was like this:



                //CargaFoto.vue
                <template>
                <div class="hello">
                <h1>{{ msg }}</h1>
                <div class="container">
                <div class="large-12 medium-12 small-12 cell">
                <label>File
                <input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
                </label>
                <button v-on:click="submitFile()">Submit</button>
                </div>
                </div>

                </div>
                </div>
                </template>

                <script>
                import axios from 'axios'

                export default {
                name: "CargaFoto",
                data() {
                return {
                msg: "Cargar Imagen de Perfil",
                file: ''
                //selectedFile: null
                };
                },
                methods: {
                submitFile(){
                /*
                Initialize the form data
                */
                let formData = new FormData();

                /*
                Add the form data we need to submit
                */
                formData.append('file', this.file);

                /*
                Make the request to the POST /single-file URL
                */
                axios.post( '/usuario/jsonimagen',
                formData,
                {
                headers: {
                'Content-Type': 'multipart/form-data'
                }
                }
                ).then(function(){
                console.log('SUCCESS!!');
                })
                .catch(function(){
                console.log('FAILURE!!');
                });
                },

                /*
                Handles a change on the file upload
                */
                handleFileUpload(){
                this.file = this.$refs.file.files[0];
                }
                }
                };
                </script>

                <!-- Add "scoped" attribute to limit CSS to this component only -->
                <style>
                #fileInput {
                display: none;
                }
                h1,
                h2 {
                font-weight: normal;
                }
                ul {
                list-style-type: none;
                padding: 0;
                }
                li {
                display: inline-block;
                margin: 0 10px;
                }
                a {
                color: #42b983;
                }
                .my-8 {
                margin-top: 4rem;
                margin-bottom: 4rem;
                }
                </style>


                In the file where the data is request, the controller is:



                //src/UsuarioController.php
                /**
                * @return JsonResponse
                * @Route("/jsonimagen", name="jsonimagen", methods="POST")

                */
                public function jsonimagen(Request $request):JsonResponse
                {
                $usuario = $this->getUser();
                $data = $request->files->get('file');
                $fileName = $usuario.'.'.$data->guessExtension();
                // moves the file to the directory where usuarios are stored
                $data->move(
                $this->getParameter('usuarios_directorio'),
                $fileName
                );
                echo $data; exit;
                return $this->json($data);
                }


                Also configure the path where the images will be loaded in the file



                //services.yaml
                parameters:
                locale: 'en'
                usuarios_directorio: '%kernel.project_dir%/public/uploads/usuarios'


                Here you can see the image loaded in this capture.



                enter image description here






                share|improve this answer













                Based on the link of a comment indicated by Fran I could see that the header was missing and then collect the data in Symfony in the same route that was already defined.



                The template file was like this:



                //CargaFoto.vue
                <template>
                <div class="hello">
                <h1>{{ msg }}</h1>
                <div class="container">
                <div class="large-12 medium-12 small-12 cell">
                <label>File
                <input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
                </label>
                <button v-on:click="submitFile()">Submit</button>
                </div>
                </div>

                </div>
                </div>
                </template>

                <script>
                import axios from 'axios'

                export default {
                name: "CargaFoto",
                data() {
                return {
                msg: "Cargar Imagen de Perfil",
                file: ''
                //selectedFile: null
                };
                },
                methods: {
                submitFile(){
                /*
                Initialize the form data
                */
                let formData = new FormData();

                /*
                Add the form data we need to submit
                */
                formData.append('file', this.file);

                /*
                Make the request to the POST /single-file URL
                */
                axios.post( '/usuario/jsonimagen',
                formData,
                {
                headers: {
                'Content-Type': 'multipart/form-data'
                }
                }
                ).then(function(){
                console.log('SUCCESS!!');
                })
                .catch(function(){
                console.log('FAILURE!!');
                });
                },

                /*
                Handles a change on the file upload
                */
                handleFileUpload(){
                this.file = this.$refs.file.files[0];
                }
                }
                };
                </script>

                <!-- Add "scoped" attribute to limit CSS to this component only -->
                <style>
                #fileInput {
                display: none;
                }
                h1,
                h2 {
                font-weight: normal;
                }
                ul {
                list-style-type: none;
                padding: 0;
                }
                li {
                display: inline-block;
                margin: 0 10px;
                }
                a {
                color: #42b983;
                }
                .my-8 {
                margin-top: 4rem;
                margin-bottom: 4rem;
                }
                </style>


                In the file where the data is request, the controller is:



                //src/UsuarioController.php
                /**
                * @return JsonResponse
                * @Route("/jsonimagen", name="jsonimagen", methods="POST")

                */
                public function jsonimagen(Request $request):JsonResponse
                {
                $usuario = $this->getUser();
                $data = $request->files->get('file');
                $fileName = $usuario.'.'.$data->guessExtension();
                // moves the file to the directory where usuarios are stored
                $data->move(
                $this->getParameter('usuarios_directorio'),
                $fileName
                );
                echo $data; exit;
                return $this->json($data);
                }


                Also configure the path where the images will be loaded in the file



                //services.yaml
                parameters:
                locale: 'en'
                usuarios_directorio: '%kernel.project_dir%/public/uploads/usuarios'


                Here you can see the image loaded in this capture.



                enter image description here







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 3 at 19:04









                juanitourquizajuanitourquiza

                389518




                389518






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53961605%2fhow-to-upload-image-from-vuejs-to-symfony-with-axios%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Monofisismo

                    Angular Downloading a file using contenturl with Basic Authentication

                    Olmecas