【问题标题】:How to upload image from VueJS to Symfony with Axios?如何使用 Axios 将图像从 VueJS 上传到 Symfony?
【发布时间】:2019-05-26 11:03:13
【问题描述】:

我在 Symfony 4 的项目中安装了 VueJS 组件没有问题,但现在我想上传一张图片。我遵循 Laravel 的这个参考:How to upload image from VueJS to Laravel with Axios?

我到达了控制器,但这就是 base 64 中的值不仅仅到达控制台消息的地方。

代码:

//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>

这是控制器代码:

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

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

答案是null我的疑问是我如何将图片上传到本地服务器。

【问题讨论】:

    标签: php symfony vue.js axios


    【解决方案1】:

    您将文件内容作为avatar 变量发送,那么为什么要尝试获取请求的data

    正确的形式是:

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

    此外,您可以省略将_method: 'POST' 添加到发送的数据,因为您已经在执行axios.post

    【讨论】:

    • 您好,感谢您的回答,但错误仍在继续,结果为空:“尝试调用类“Symfony\Component\HttpFoundation\Request”的名为“文件”的未定义方法。”跨度>
    • @juanitourquiza,你Request应该是Illuminate\Http\Request
    • 感谢您的回答,但我使用的是 symfony 而不是 laravel。我已经收集了数据,但我将它们放在临时文件夹中
    • 你把我弄糊涂了,我以为你在使用 Laravel。
    【解决方案2】:

    根据Fran 指示的评论的link,我可以看到标头丢失,然后在已定义的同一路由中收集Symfony 中的数据。

    模板文件是这样的:

    //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>
    

    在请求数据的文件中,控制器是:

    //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);
    }
    

    还要配置文件中加载图片的路径

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

    在这里您可以看到在此捕获中加载的图像。

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 2019-01-21
      • 2018-08-24
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      • 2018-08-20
      • 2019-04-01
      • 1970-01-01
      相关资源
      最近更新 更多