gella's avatar
Level 1

Upload file with form

Hello all, I am trying to add a file in the form, but I'm new in Vue.js and I'm having troubles with that. Can anyone help please?

<div class="form-group ">
       {!! Form::label('category','Category') !!}
       {!! Form::text('cat',null,['class'=>'form-control','v-model'=>'cat']) !!}
</div>
 <div class="form-group ">
        {!! Form::label('image','Photo') !!}
        {!! Form::file('image',null,['class'=>'form-control','v-model'=>'image','v-model'=>'file','ref'=>'file','v-on:change'=>'handleFileUpload()') !!}
 </div>

data:{ videos:[],

               cat : null,
                image: '',}

methods:{ handleFileUpload(){ this.file = this.$refs.file.files[0]; },

            saveVideo(){

                var formData = new FormData();
                formData.append('image', this.file);
                formData.append('cat, this.category);
              
                $.ajax({
                    url:'/settings/video/store',
                    type:'post',
                    processData: false,
                    contentType: false,
                    data: formData,
                    success:function(){
                    }
                })

            },

Image is sent as empty string

0 likes
9 replies
D9705996's avatar

You have two v-model on your file input

'v-model'=>'image','v-model'=>'file'

I would remove these as you are using your handleFileUpload() method to update your data. You also are missing a square bracket at the end of

['class'=>'form-control','v-model'=>'image','v-model'=>'file','ref'=>'file','v-on:change'=>'handleFileUpload() // add ] here

Your also missing a single quote after cat in

formData.append('cat, this.category);
gella's avatar
Level 1

@D9705996 I did all of them, but still the image is sent as empty string. I tried using multipart/form-data but it throws an error

D9705996's avatar

Where do you see the image as an empty string? Are you getting any error messages either in your front end or back end

gella's avatar
Level 1

@D9705996 I can see it in the response header at network, also nothing is saved in database

Ishatanjeeb's avatar

You make mistake here,please replace your form by

<div class="form-group ">
       {!! Form::label('category','Category') !!}
       {!! Form::text('cat',null,['class'=>'form-control','v-model'=>'cat']) !!}
</div>
 <div class="form-group ">
        {!! Form::label('image','Photo') !!}
        {!! Form::file('image',['class'=>'form-control','v-model'=>'image','v-model'=>'file','ref'=>'file','v-on:change'=>'handleFileUpload()') !!}
 </div>
D9705996's avatar

Have you checked in vue dev tools what your data looks like when to you trigger handleFormUpload() in your form?

gella's avatar
Level 1

@Ishatanjeeb If I remove null from image, it throws an error in the method handleFormUpload, Cannot read property '0' of undefined

Please or to participate in this conversation.