jQuery Ajax File Upload in Laravel

Today, We want to share with you jQuery Ajax File Upload in Laravel.In this post we will show you multiple image upload in laravel using ajax, hear for formdata jquery file upload in laravel we will give you demo and example for implement.In this post, we will learn about jquery ajax image upload preview codeigniter with an example.

jQuery Ajax File Upload in Laravel

There are the Following The simple About jQuery Ajax File Upload in Laravel Full Information With Example and source code.


As I will cover this Post with live Working example to develop How to make ajax image upload with laravel 5, so the laravel ajax crud example with image upload for this example is following below.

Step 1: Define Laravel Route

/dsp_salon/routes/web.php

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

Route::match(['get', 'post'], 'ajax-image-upload', '[email protected]_upload_img');
Route::delete('ajax-remove-image/{filename}', '[email protected]');

Step 2: Create View

/dsp_salon/resources/views

Read Also:  PHP check laravel version using command

Create file product_img_uploaded.blade.php in /dsp_salon/resources/views.

<!DOCTYPE html>
<html>
<head>
    <title>Ajax Image Upload with Laravel - pakainfo.com</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="display_img_img" src="{{asset('medias/no_any_loading_img.jpg')}}"/>
        <i id="img_uploading" class="pakainfo 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="pakainfo glyphicon glyphicon-edit"></i> Change
        </a>  
        <a href="javascript:removeFile()" style="color: red;text-decoration: none;">
            <i class="pakainfo glyphicon glyphicon-trash"></i>
            Remove
        </a>
    </p>
    <input type="file" id="file" style="display: none"/>
    <input type="hidden" id="uploaded_img_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 product_data = new FormData();
        product_data.append('file', img.files[0]);
        product_data.append('_token', '{{csrf_token()}}');
        $('#img_uploading').css('display', 'block');
        $.ajax({
            url: "{{url('ajax-image-upload')}}",
            data: product_data,
            type: 'POST',
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.fail) {
                    $('#display_img_img').attr('src', '{{asset('medias/no_any_loading_img.jpg')}}');
                    alert(data.errors['file']);
                }
                else {
                    $('#uploaded_img_name').val(data);
                    $('#display_img_img').attr('src', '{{asset('medias')}}/' + data);
                }
                $('#img_uploading').css('display', 'none');
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
                $('#display_img_img').attr('src', '{{asset('medias/no_any_loading_img.jpg')}}');
            }
        });
    }
    function removeFile() {
        if ($('#uploaded_img_name').val() != '')
            if (confirm('Are you sure want to remove Product picture?')) {
                $('#img_uploading').css('display', 'block');
                var product_data = new FormData();
                product_data.append('_method', 'DELETE');
                product_data.append('_token', '{{csrf_token()}}');
                $.ajax({
                    url: "ajax-remove-image/" + $('#uploaded_img_name').val(),
                    data: product_data,
                    type: 'POST',
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        $('#display_img_img').attr('src', '{{asset('medias/no_any_loading_img.jpg')}}');
                        $('#uploaded_img_name').val('');
                        $('#img_uploading').css('display', 'none');
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
                    }
                });
            }
    }
</script>
</body>
</html>

Step 3: Make a Laravel 5.8 Controller

/dsp_salon/app/Http/Cotrollers

Read Also:  Laravel jQuery Ajax Upload Multiple Images

Create controller file ProductController in /dsp_salon/app/Http/Cotrollers.

<?php
namespace App\Http\Controllers;

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

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

    public function removeFiles($filename)
    {
        File::delete('medias/' . $filename);
    }
}

Web Programming Tutorials Example with Demo

Read :

Read Also:  Laravel 7 jQuery Ajax Image Upload Tutorial

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about jQuery Ajax File Upload in Laravel.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.