Search code examples
laravelvue.jsfile-uploadbase64

How to upload multiple images with base64 in laravel & vue-js


I have been trying to upload multiple images with base64 but it uploads only the second one. and Is there any easy way to upload images in larvel-vueJS instead of base 64.

this is the Vue-js method:

updateIMG(e){
                // console.log('uploaded');
               let file = e.target.files[0]
               let reader = new FileReader();
               if(file['size'] < 9111775){
                   reader.onloadend = (file) => {
                       this.landingform.logo = reader.result;
                       this.landingform.landingBg = reader.result;
                   }
                   reader.readAsDataURL(file)            
               }else {
                   swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'You are uploading a large fiel!',
                        footer: 'You are authorized to upload files less than 10MB.'
                    })
               }

the method called like this:

<input type="file" @change="updateIMG" name="logo" class="form-input">

and this is my controller:

public function updateLanding(Request $request)
    {

        $landnginIMG = LandingImage::whereIn('id', [1]);

         if ($request->logo){
            $name = time().'.' . explode('/', explode(':', substr($request->logo, 0, 
            strpos($request->logo, ';')))[1])[1];

            \Image::make($request->logo)->save(public_path('img/landing/').$name);
            $request->merge(['logo' => $name]);

        };
        if ($request->landingBg){
            $bgname = time().'.' . explode('/', explode(':', substr($request->landingBg, 0, 
            strpos($request->landingBg, ';')))[1])[1];

            \Image::make($request->landingBg)->save(public_path('img/landing/').$bgname);
            $request->merge(['landingBg' => $bgname]);
        };

        $landnginIMG->update([
            'logo'=> $request ['logo'],
            'landingBg'=> $request ['landingBg'],
            ]);
        return ['message' => 'all is done'];
    }

Solution

  • There are a few factors your must follow.

    First

    Your form should let you select multiple files

    Second

    Your JavaScript must handle all of those files when selected. Check this line of your code.

     // console.log('uploaded');
     let file = e.target.files[0]
     let reader = new FileReader();
    

    e.target.files[0] is taking the first file. You should loop and go through all files.

    let files = e.target.files;
    

    Now, use JavaScript foreach loop and convert each file to base64 and store them on array. Then, send that array to sever.

    On the server, do the same. You will receive an array so you should loop through each and convert it back to image and save it.

    Thanks.