monstajamss's avatar

Laravel and Vue Js File (Image) Upload

I am trying to upload image in my laravel application but anytime i click the update button i get the validation error i set. And i only see File in the vue js dev tools.

Here is my code

<form @submit.prevent enctype="multipart/form-data">
   <input class="form-control" type="file" name="logo_image" @change="selectFile"/>
</form>

Script

data() {
        return {
            client: [],
            services:[],
            errors: {},
            success: false,
            loaded: true,
        }
    },
selectFile(e){
            this.client.logo_image = e.target.files[0]     
        },
        updateClient(){
            if(this.loaded) {
                this.loaded = false,
                this.success = false,
                this.errors = {};
                const data = new FormData()
                data.append('client', this.client.logo_image)
                axios.post(  (this.$apiAdress + '/api/main-clients/update/' + this.$route.params.id + '?token=' + localStorage.getItem("api_token")),
                    this.client, data
                )
                .then(response => {
                    if(response.status === 200 ) {
                        this.client = {};
                        this.loaded = true;
                        this.success = true;
                        this.$router.push({ path: '/main-clients' });
                    }
                }).catch(error => {
                    this.loaded = true;
                    if(error.response.status === 422) {
                        this.errors = error.response.data.errors || {};
                    }
                })
            }
        }

Controller

 public function updateClient(ClientRequest $request)
    {
        $clientId = $request->route('id');

        $data = $request->only([
            'client_name', 
            'email', 
            'phone_number',
            'mobile_number',
            'bank_name',
            'sort_code',
            'account_number',
            'address_1',
            'address_2',
            'address_3',
            'town',
            'postalcode',
            'vat_number',
        ]);

        if($request->has('logo_image') && $request->logo_image !='')
         {
            $client = $this->clientRepository->updateClientDetails($clientId, $data);
            $path = str_replace('\', '/',public_path('clients/'.$client->logo_image));
            if(file_exists($path)){
                File::delete($path);
            }
             $imageName = $request->client_name.'.'.$request->logo_image->extension();  
         
             $request->logo_image->move(public_path('clients'), $imageName);
 
             $data['logo_image'] = $imageName;
         }

        $client = $this->clientRepository->updateClientDetails($clientId, $data);
        $client->services()->sync($request->services_id);
        $client->update($request->all());

        return response()->json(null, 200)->setStatusCode(200);
    }

ClientRequest.php

 public function rules()
    {
        return [
            'services_id' => 'required',
            'client_name' => 'required',
            'email' => 'required|email',
            'phone_number' => 'required',
            'mobile_number' => 'required',
            'address_1' => 'required',
            'address_2' => 'required',
            //'address_3' => 'required',
            'town' =>'required',
            'postalcode' => 'required',
            'vat_number' => 'required',
            'logo_image' => 'image|mimes:jgep,png,jpg|max:2048',
        ];
    }

How do i make the file upload work during update?

0 likes
13 replies
Tray2's avatar

Is your form set to multipart?

monstajamss's avatar

@Tray2 Uploading of image works without using vue js.

But with vuejs and api it does not store into the database. Instead the file property is there(which does not store also)

monstajamss's avatar

Now i can see base64 on the client object in vuejs dev tools

monstajamss's avatar

I was able to read the image using this

selectFile(e){
            let file = e.target.files[0]
            let reader = new FileReader()
            reader.onloadend = () => {
                this.client.logo_image = reader.result
            }
            reader.readAsDataURL(file)
        },

but it fails with validation

 'logo_image' => 'image|mimes:jgep,png,jpg|max:2048',

i did this in my controller

if($request->has('logo_image') && $request->logo_image !='')
         {
$exploded = explode(';',$request->logo_image);
            $decoded = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $exploded[1]));
            $imageName = $request->client_name.'.'.$request->logo_image->extension();  
        
            $request->logo_image->move(public_path('clients'), $imageName, $decoded);

            $data['logo_image'] = $imageName;
         }
xuma's avatar

@monstajamss Reference to your first post there is no logo_image in your form data. You named it client.

data.append('client', this.client.logo_image)

it should be;

data.append('logo_image', this.client.logo_image)

Please or to participate in this conversation.