Laravel 6 ajax image upload with preview tutorial from Scratch

laravel 6 Ajax Image Upload – Today we will show you how to upload image using ajax. Also we will see how to validate the image.

Also we will learn how to show image preview before sending the file to the server.

When we upload the image we will validate image using server side validation. We will upload the image using JQuery Ajax without page refresh and reload.

Laravel Ajax Image Upload Tutorial

Contents

  • Install Laravel App
  • Make Route
  • Create Controller & Methods
  • Create Blade View
  • Make Folder
  • Start Development Server
  • Conclusion

Install Laravel App

First, We need a fresh laravel setup. Use the below command to create fresh laravel project.

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

Create Route

We will create two routes in web.php file. Go to app/routes/web.php file and create two route.

 Route::get('photo', '[email protected]');
Route::post('save-photo', '[email protected]');

Create Controller

We need to create a controller name ImageController. Use the below command and create Controller :

php artisan make:controller ImageController

After successfully create controller go to app/controllers/ImageController.php and put the below code :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageController extends Controller
{
    public function index() {
		return view('image');
	}

	public function save(Request $request)
	{
		request()->validate([
			'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
		]);

		if ($files = $request->file('image')) {

			$image = $request->image->store('public/images');
			
			return Response()->json([
				"success" => true,
				"image" => $image
			]);

		}

		return Response()->json([
				"success" => false,
				"image" => ''
			]);

	}
}
 

Here you can see. We are using below single line to upload the file

$request->image->store('public/images');

Using the above code you will be above to upload the file and laravel will rename the file it self. If you want your own name then use the below code

$request->photo->storeAs('image', 'filename.jpg');

Create Blade View

In this step we need to create blade view file. Go to app/resources/views and create one file name image.blade.php :

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>W3path | @yield('title') - W3path.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <link rel="icon" href="{{ url('public/image/w3path-favicon.png') }}" sizes="32x32" />
  <style>
   .container{
    padding: 0.5%;
   } 
</style>
</head>
<body>

  <nav class="navbar navbar-expand-sm bg-primary navbar-dark">
    <a class="navbar-brand" href="{{ url('/') }}">w3path</a>
  </nav>
    <div class="container mt-4">
        <div class="row">
            <div class="col-sm-12">
                <h4>Upload image using ajax</h4>
            </div>
        </div>
        <hr />
     
        <form method="POST" enctype="multipart/form-data" id="upload_image_form" action="javascript:void(0)" >
                 
            <div class="row">
                <div class="col-md-12 mb-2">
                    <img id="image_preview_container" src="{{ asset('public/image/image-preview.png') }}" 
                        alt="preview image" style="max-height: 150px;">
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="image" placeholder="Choose image" id="image">
                        <span class="text-danger">{{ $errors->first('title') }}</span>
                    </div>
                </div>
                 
                 
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
            </div>     
        </form>
    </div>
</body>
</html>

Now we will implement laravel ajax image upload script, put the below script after closing of body tag.

<script type="text/javascript">
    
    $(document).ready(function (e) {
 
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $('#image').change(function(){
         
            let reader = new FileReader();
            reader.onload = (e) => { 
              $('#image_preview_container').attr('src', e.target.result); 
            }
            reader.readAsDataURL(this.files[0]); 

        });

        $('#upload_image_form').submit(function(e) {
            e.preventDefault();

            var formData = new FormData(this);

            $.ajax({
                type:'POST',
                url: "{{ url('save-photo')}}",
                data: formData,
                cache:false,
                contentType: false,
                processData: false,
                success: (data) => {
                    this.reset();
                    alert('Image has been uploaded successfully');
                },
                error: function(data){
                    console.log(data);
                }
            });
        });
    });

</script>

Create Folder

Now create a folder name images where we store our images :

Go to public folder 
=> first create folder name images

Start Development Server

In this step, we will use the php artisan serve command . It will start your server locally

 php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080

Now we are ready to run our example so run bellow command to quick run.

http://127.0.0.1:8000/photo

Conclusion

In this laravel ajax image upload example, we have successfully uploaded image into datatabase and folder and we have successfully image upload without page refresh and reload using ajax.

If you have any questions or thoughts to share, use the comment form below to reach us.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *