Vue.js-在标头中使用多部分/表单数据时,验证无法在axios中上载

宝儿 · 05月28日

我正在使用BootstrapVueVeeValidate和axios作为HTTP客户端构建Laravel + Vue.js SPA(单页应用程序)

在axios内部,当我 multipart/form-data; boundary=${uploadForm._boundary}用作Content-Typein时headers ,Laravel Controller方法中的所有验证都会失败

但是,如果我'content-type': 'multipart/form-data'在其中使用header 则验证会起作用,file输入字段除外file在Laravel控制器方法中,字段变为空。

这发生在组件内EditProfile.vue那里的内容是:

<template>
<ValidationObserver ref="form" v-slot="{ passes }">

        <div id="registration_form">

            <div id="form_title" class="text-center">Edit Your Profile</div>
            <div v-html="result" class="result text-center"></div>


            <b-form name="uploadForm" @submit.prevent="passes(onSubmit)" @reset="resetForm"  enctype="multipart/form-data">


                <ValidationProvider vid="name" rules="required|min:2" name="name" v-slot="{ valid, errors }">
                    <b-form-group
                            label="User Name:"
                            label-for="exampleInput1"

                    >
                        <b-form-input
                                type="text"
                                disable-leading-trailing-space
                                v-model="name"
                                plaintext
                                :state="errors[0] ? false : (valid ? true : null)"
                                placeholder="Enter your name"
                        ></b-form-input>
                        <b-form-invalid-feedback id="inputLiveFeedback">{{ errors[0] }}</b-form-invalid-feedback>
                    </b-form-group>
                </ValidationProvider>



                <ValidationProvider vid="photo" rules="required" name="photo" v-slot="{ valid, errors }">
                    <b-form-group
                            label="Photo:"
                            label-for="exampleInput1"
                    >


                        <b-form-file

                                accept="image/x-png,image/gif,image/jpeg"
                                v-model="file"
                                :state="Boolean(file)"
                                placeholder="Choose a file or drop it here..."
                                drop-placeholder="Drop file here..."
                                @change="onFileChange" enctype="multipart/form-data"
                        ></b-form-file>
                        <b-form-invalid-feedback id="inputLiveFeedback">{{ errors[0] }}</b-form-invalid-feedback>
                        <div class="mt-3">Selected file: {{ file ? file.name : '' }}</div>

                        <!-- Plain mode -->
                        <!--<b-form-file v-model="file2" class="mt-3" plain></b-form-file>
                        <div class="mt-3">Selected file: {{ file2 ? file2.name : '' }}</div>-->

                        <div id="preview">
                            <img v-if="url" :src="url" />
                        </div>

                    </b-form-group>
                </ValidationProvider>





                <b-button type="submit" variant="primary">Submit</b-button>
                <b-button type="reset" variant="danger">Reset</b-button>
            </b-form>

        </div><!-- end of id registration_form-->
    </ValidationObserver>
</template>

在JS部分,我有:

<script>


    import { ValidationObserver, ValidationProvider } from "vee-validate";

     export default {
        name: "EditProfile",
        props: {

        },

        components: {
            ValidationObserver,
            ValidationProvider


        },
        data: () => ({

            name: "",
            photo:"",
            file:"",
            url:"",  
            result:''

        }),

        methods: {
            onFileChange(e) {
                this.file = e.target.files[0];
                this.url = URL.createObjectURL(this.file);
            },
        onSubmit() {
                console.log("Form submitted yay!");


                this.result='<span class="wait">Please wait ...</span>';

                axios.post('/update_profile_now',
                    {
                       name: this.name,
                       photo:this.file

                    }, // the data to post
                    {


                        headers: {

                            //Accept: 'application/json',

                           'Content-Type':  `multipart/form-data; boundary=${uploadForm._boundary}`

                        }



                    })
                    .then(response => {

                        if(response.data.success){

                            this.result='<span class="succes">Registration completed !!</span>';
                        }else{

                            this.$refs.form.setErrors(response.data.errors);

                            this.result='<span class="error">Invalid data !!</span>';
                        }




                    })
                    .catch(error => {

                        if(typeof error !=="undefined"){

                            console.log(error);
                        }

                    });

                //    .finally(() => this.loading = false)
            },
            resetForm() {
                this.name = "";

                this.result='';

                requestAnimationFrame(() => {
                    this.$refs.form.reset();
                });
            }
        }
    };

</script>

在相应的Laravel控制器方法中,我有:

 public function update_profile_now(Request $request)
    {


        $rules = array(

            'name' => 'required | min:4',
            'photo'=> 'image|mimes:jpeg,png,jpg|max:2048'
        );

        $validator = Validator::make(Input::all(), $rules);

        // Validate the input and return correct response
        if ($validator->fails())
        {
            return Response::json(array(
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray()

            ), 200); 
        }

        //file uploading code goes here 

        return Response::json(array('success' => true), 200);




   }

我想要的是file将提交内部带有输入的表单,然后在文件上传和其他工作之后从该方法发送JSON响应。

So what should be the correct header or do I need to adopt any other means ?

回答(2)
时间
伽罗理查德
2 · 2020-05-28 15:33:27

我建议VeeValidation您在提交表单后使用它来验证您的表单。

它确实是最简单和最甜蜜的验证方法。

您可以从这里安装。VeeValidation链接

C
Chloe
1 · 2020-05-28 15:33:27

你的回答

加载中...
⌘+Return 发表
发表

温馨提示:登录后可发表评论或回复

关闭,朕知道了

扫码关注微信公众号或小程序