How to make ajax image upload with laravel 5

Published Date: 25-Nov-2017 | Tags: Laravel 5.5  Ajax  Javascript  Image Upload  

This tutorial I want to show you how to upload image via jquery ajax with laravel 5.5.

Suppose that your server is running on port 80 and your project folder is /demo.

 

Step 1: Add Route

Add these lines to this file /demo/routes/web.php.

Route::match(['get', 'post'], 'ajax-image-upload', 'ImageController@ajaxImage');
Route::delete('ajax-remove-image/{filename}', 'ImageController@deleteImage');

 

Step 2: Create View

Create file ajax_image_upload.blade.php in /demo/resources/views.

<!DOCTYPE html>
<html>
<head>
    <title>Ajax Image Upload with Laravel</title>
</head>
<body style="background: lightgrey">
<center>
    <br/><br/>
    <div style="width:350px;height: 350px; border: 1px solid whitesmoke ;text-align: center;position: relative" id="image">
        <img width="100%" height="100%" id="preview_image" src="{{asset('images/noimage.jpg')}}"/>
        <i id="loading" class="fa fa-spinner fa-spin fa-3x fa-fw" style="position: absolute;left: 40%;top: 40%;display: none"></i>
    </div>
    <p>
        <a href="javascript:changeProfile()" style="text-decoration: none;">
            <i class="glyphicon glyphicon-edit"></i> Change
        </a>&nbsp;&nbsp;
        <a href="javascript:removeFile()" style="color: red;text-decoration: none;">
            <i class="glyphicon glyphicon-trash"></i>
            Remove
        </a>
    </p>
    <input type="file" id="file" style="display: none"/>
    <input type="hidden" id="file_name"/>
</center>
<!-- JavaScripts -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"
        integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="https://use.fontawesome.com/2c7a93b259.js"></script>
<script>
    function changeProfile() {
        $('#file').click();
    }
    $('#file').change(function () {
        if ($(this).val() != '') {
            upload(this);

        }
    });
    function upload(img) {
        var form_data = new FormData();
        form_data.append('file', img.files[0]);
        form_data.append('_token', '{{csrf_token()}}');
        $('#loading').css('display', 'block');
        $.ajax({
            url: "{{url('ajax-image-upload')}}",
            data: form_data,
            type: 'POST',
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.fail) {
                    $('#preview_image').attr('src', '{{asset('images/noimage.jpg')}}');
                    alert(data.errors['file']);
                }
                else {
                    $('#file_name').val(data);
                    $('#preview_image').attr('src', '{{asset('uploads')}}/' + data);
                }
                $('#loading').css('display', 'none');
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
                $('#preview_image').attr('src', '{{asset('images/noimage.jpg')}}');
            }
        });
    }
    function removeFile() {
        if ($('#file_name').val() != '')
            if (confirm('Are you sure want to remove profile picture?')) {
                $('#loading').css('display', 'block');
                var form_data = new FormData();
                form_data.append('_method', 'DELETE');
                form_data.append('_token', '{{csrf_token()}}');
                $.ajax({
                    url: "ajax-remove-image/" + $('#file_name').val(),
                    data: form_data,
                    type: 'POST',
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        $('#preview_image').attr('src', '{{asset('images/noimage.jpg')}}');
                        $('#file_name').val('');
                        $('#loading').css('display', 'none');
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
                    }
                });
            }
    }
</script>
</body>
</html>

 

Step 3: Create Controller

Create controller file ImageController in /demo/app/Http/Cotrollers.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;

class ImageController extends Controller
{
    public function ajaxImage(Request $request)
    {
        if ($request->isMethod('get'))
            return view('ajax_image_upload');
        else {
            $validator = Validator::make($request->all(),
                [
                    'file' => 'image',
                ],
                [
                    'file.image' => 'The file must be an image (jpeg, png, bmp, gif, or svg)'
                ]);
            if ($validator->fails())
                return array(
                    'fail' => true,
                    'errors' => $validator->errors()
                );
            $extension = $request->file('file')->getClientOriginalExtension();
            $dir = 'uploads/';
            $filename = uniqid() . '_' . time() . '.' . $extension;
            $request->file('file')->move($dir, $filename);
            return $filename;
        }
    }

    public function deleteImage($filename)
    {
        File::delete('uploads/' . $filename);
    }
}

 

Step 4: Test

Open your browser and type http://localhost/demo/public/ajax-image-upload. Then you will see it.

laravel-ajax-image-upload

Hope you can do it.


Demo


Related Posts

© 2018 All Rights Reserved.