How To Upload Image Using Ajax In Laravel

admin_img Posted By Bajarangi soft , Posted On 23-01-2021

We can upload image using ajax with Json response.

How To Upload Image Using Ajax In Laravel

Step 1:Create a table and model for Image Uploading.

class Password extends Model
{
    public $table = 'password';

    protected $fillable = [
        'name','password','confirm_password','image'
    ];
}

 


Step: 2 Create a View file like image.blade.php and add image fields and make one aajx script for image uploading
resources/views/email.blade.php.
 

<html>
    <head>
        <title>Image</title>
        <link rel='stylesheet' href='style.css'/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-latest.min.js"></script>
        <script src='script.js'></script>

    </head>
    <br>
    <body>
        <div id="main_container" class="container">
            <div class="alert" id="message" style="display: none"></div>
            <div class="row">
              <form method="post" id="form" enctype="multipart/form-data">

                <div class="col-md-6">
                        {{ csrf_field() }}
                        <div class="form-group">
                            <div id="birth_date_input" class="control-label">Image: 
                                <input type="file" id="image" name="image">

                            </div>
                        </div>
                </div>     
                <div class="col-md-6">
                    <button id="imgbtn" class="btn btn-success" style="margin-top: 25px;">Upload</button>
                </div>
                
                <div class="row">
                    <div class="col-md-12">
                        <div id="age_container"><span id="exact_age"></span></div>
                        <div id="age_container"><span id="exact_age1"></span></div>
                        <div id="age_container"><span id="exact_age2"></span></div>
                    </div>

                </div>
               </form>
            </div>
            <span id="uploaded_image"></span>
        </div>

<script>
    $(document).ready(function(){

        $('#form').on('submit', function(event){
            event.preventDefault();
            $.ajax({
                url:"{{ url('upload') }}",
                method:"POST",
                data:new FormData(this),
                dataType:'JSON',
                contentType: false,
                cache: false,
                processData: false,
                success:function(data)
                {
                    // alert(data.message);
                    $('#message').css('display', 'block');
                        $('#message').html(data.message);

                    setTimeout(function() {
                        $('#message').fadeOut('slow');
                    }, 5000);
                    // $('#message').html(data.message);
                    $('#message').addClass(data.class_name);
                    $('#uploaded_image').html(data.uploaded_image);
                }
            })
        });

    });
</script>
</body>
</html>


Step 3: Make controller file for validating image and uploading image to the folder and make response of success image uploading.
 

function store(Request $request)
    {

        $input = $request->all();

        $this->validate($request, [

            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);
        $input = $request->except('image');
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $name = time() . '.' . $image->getClientOriginalExtension();
            $destinationPath = public_path('/images');
            $image->move($destinationPath, $name);
            $input['image'] = $name;
            return response()->json([
                'message' => 'Image Upload Successfully..',                 
                'class_name' => 'alert-success'
            ]);

        }
        return response()->json([
            'message' => 'something went wrong',
            'class_name' => 'alert-success'
        ]);
    }

 


Step: 4 Make a route for connection with controller.
app/Http/routes.php
 

Route::get('image', 'ImageController@index');
Route::post('/upload', 'ImageController@store');

Related Post