How To Upload Multiple Images Using VueJs and Laravel

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

we will create a post route with a controller. implement code in controller to upload images. Then install npm, vue and axios. After that, we will write a code of the component. In a component file, we will write code of image upload using vue js.So today we discuss how to do it.

How To Upload Multiple Images Using VueJs and Laravel

Let's learn

1.Install new laravel project to implement code. https://laravel.com/docs/5.8/installation

composer create-project --prefer-dist laravel/laravel blog

run above command in command prompt.

2.Install node.js package for blog project . click here to download it.
3.Install npm package for blog project.
click here to see the documentation.Install the dependencies in the local node_modules folder.

npm install

run above command in terminal.
4.Connect database with blog project.

DB_DATABASE=VUEjs
DB_USERNAME=root
DB_PASSWORD=

5.Use Below Code to upload multiple images.

php artisan make:model multipleimage -mcr

6.Open model blog/app/multipleimage.php and implement code as below code.
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class multipleimage extends Model
{
    protected $fillable = [
        'file',
    ];
}

7.Open controller blog/app/Http/Controllers/multipleimage.php and implement code as below code.
<?php

namespace App\Http\Controllers;

use App\multipleimage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Intervention\Image\ImageManagerStatic as Image;

class MultipleimageController extends Controller
{
    public function multiple(Request $request)
    {
        if ($request->hasFile('files')) {
            foreach ($request->file('files') as $file) {
                $filename = str_random(5) . "." . $file->getClientOriginalExtension();
                $path = $file->move(public_path('upload/image'), $filename);
                $thumbnail_resize = Image::make($path);
                $thumbnail_resize->resize(224, 126);
                $thumbnail_resize->save(public_path('upload/thumbnail/thumbnail' . $filename));

                $Image_resize = Image::make($path);
                $Image_resize->resize(1280, 720);
                $Image_resize->save(public_path('upload/images/images' . $filename));

                $caseInput = [];
                $caseInput['file'] = $filename;
                multipleimage::create($caseInput);
            }

        }
        return 'done';
    }
}

8.Create image.vue in blog/resources/js/components folder and implement below code in it.
<template>
    <div class="container">
        <div class="row justify-content-center ">
            <div class="container">
                <h2>Select an image</h2>
                <input type="file" ref="file" name="file[]" multiple="multiple"  @change="onFileChange">
                <div class="jumbotron mt-5">
                    <div class="row">
                        <div v-for="(image, index) in images">
                            <button class="btn btn-dark btn-xs" @click="removeImage(index)">Remove image</button>
                            <img class="preview" :src="image" />
                        </div>
                    </div>
                </div>
                <button class="btn btn-success btn-xs"  @click="submitFile">Upload</button>
            </div>
        </div>
    </div>
</template>
<script>
    import Vue from "vue";

    export default {
        mounted() {
            console.log('Component mounted.')
        },

        data(){
            return{
                files: [],
                images: []
            }
        },

        methods: {
            onFileChange(e) {
                var files = e.target.files || e.dataTransfer.files;
                if (!files.length)
                    return;
                this.createImage(files);
            },
            createImage(files) {
                var vm = this;

                for (var index = 0; index < files.length; index++) {
                    var reader = new FileReader();
                    reader.onload = function(event) {
                        const imageUrl = event.target.result;
                        vm.images.push(imageUrl);
                    }
                    reader.readAsDataURL(files[index]);
                }
            },
            removeImage(index) {
                this.images.splice(index, 1)
            },

            submitFile(e){

                let formData = new FormData();

                for( var i = 0; i < this.$refs.file.files.length; i++ ){
                    let file = this.$refs.file.files[i];
                    console.log(file);
                    formData.append('files[' + i + ']', file);
                }

                axios.post( 'http://localhost/blog/public/multiple-image', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        },
                    }
                ).then(function(){
                })
                    .catch(function(){
                    });
                Vue.$toast.open('Image Uplaoded Successfully!!');
                // window.location.reload();
                window.location.reload();
            },
        }
    }
</script>
<style type="text/css">
    .preview{
        display: flex;
        justify-content: center;
        align-items: center;
        height: 120px;
        width: 120px;
        margin-right: 11px;
        margin-top: 10px;
    }
</style>


9.Include Image.vue file into blog/resources/js/app.js as below
require('./bootstrap');

window.Vue = require('vue');

import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Vue from 'vue';
import VueToast from 'vue-toast-notification';
// Import one of available themes
import 'vue-toast-notification/dist/theme-default.css';


Vue.use(VueToast);
Vue.$toast.open('You did it!');
Vue.$toast.open({/* options */});

Vue.$toast.clear();

const example = require('./components/ExampleComponent.vue').default;
const Image = require('./components/Image.vue').default;
const routes=[
    {
               path: '/Image',
                component: Image
            },
];

const router=new VueRouter({
    routes
});
const app = new Vue({
    el: '#app',
    router,
    data:{

    }
});

10.Now implement code to view in vue file.
home.blade.php
@extends('layouts.app')

@section('content')
    <router-view></router-view>
@endsection

welcome.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @auth
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ route('login') }}">Login</a>

                        @if (Route::has('register'))
                            <a href="{{ route('register') }}">Register</a>
                        @endif
                    @endauth
                </div>
            @endif
    </body>
</html>

11.Create route for uploading file.
Route::post('/multiple-image', 'MultipleimageController@multiple')->name('multiple-image');

12.Run command npm run watch.

npm run dev  active and  updates only when you run command.
npm run watch does the same, but then it stays active and "watches" for updates.vue and .js files. If it detects a change so you can just refresh the page.


13.Now run below url in google chrome.

http://localhost/blog/public/

Related Post