codovel

We no longer support this blog. Please visit this site instead. www.codovel.com

Saturday, June 18, 2016

Laravel upload image file with ajax loading

Suppose that your project root folder is here C:\wamp\www\test_laravel.

Please download this file public.rar and extract to your public folder (C:\wamp\www\test_laravel\public)

Step 1: Edit route file (C:\wamp\www\test_laravel\app\Http\routes.php) and add
Route::controller('tutorial', 'TutorialController');

Step 2: Create view file upload_image_profile.blade.php in C:\wamp\www\test_laravel\resources\views\tutorial (please create tutorial folder if not exist)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="_token" content="{{ csrf_token() }}"/>
    <title>Laravel Tutorials</title>
    <!-- Styles -->
    <link href="{{ asset('bootstrap-3.3.6/css/bootstrap.min.css') }}" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
    <div class="row"></div>
    <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-4">
            <center>
                <br/>

                <div style="width:200px;height: 200px;border: 1px solid whitesmoke;text-align: center" id="img1">
                    <img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>
                </div>
                <br/>

                <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="file1" style="display: none"/>
            </center>
        </div>
        <div class="col-md-4"></div>
    </div>
</div>
<!-- JavaScripts -->
<script src="{{ asset('js/jquery-1.11.2.min.js') }}"></script>
<script src="{{ asset('bootstrap-3.3.6/js/bootstrap.min.js') }}"></script>
<script>
    var filename = '';
    function changeProfile() {
        $('#file1').click();
    }
    $('#file1').change(function () {
        if ($(this).val() != '') {
            upload();

        }
    });
    function upload() {
        var file_data = $('#file1').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        $.ajaxSetup({
            headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
        });
        $('#img1').html('<img src="{{asset('images/loader.gif')}}" style="padding-top: 40%"/>');
        $.ajax({
            url: "{{url('tutorial/upload-image-file')}}", // point to server-side PHP script
            data: form_data,
            type: 'POST',
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData: false,
            success: function (data) {
                if (data.fail) {
                    $('#img1').html('<img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>');
                    alert(data.errors['file']);
                }
                else {
                    filename = data;
                    $('#img1').html('<img width="100%" height="100%" src="{{asset('uploads')}}/' + data + '"/>');
                }
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
                $('#img1').html('<img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>');
            }
        });
    }
    function removeFile() {
        if (filename != '')
            if (confirm('Are you sure want to remove profile picture?'))
                $.ajax({
                    url: "{{url('tutorial/remove-image-file')}}/" + filename, // point to server-side PHP script
                    type: 'GET',
                    contentType: false,       // The content type used when sending data to the server.
                    cache: false,             // To unable request pages to be cached
                    processData: false,
                    success: function (data) {
                        $('#img1').html('<img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>');
                        filename = '';
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
                    }
                });
    }
</script>
</body>
</html>


Step 3: Create controller file TutorialController.php in here C:\wamp\www\test_laravel\app\Http\Controllers
<?php
namespace App\Http\Controllers;

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

class TutorialController extends Controller
{
    public function getUploadImageFile()
    {
        return view('tutorial.upload_image_file');
    }
    public function postUploadImageFile(Request $request)
    {
        $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->getMessageBag()->toArray()
            );
        $extension = $request->file('file')->getClientOriginalExtension(); // getting image extension
        $dir = 'uploads/';
        $filename = uniqid() . '_' . time() . '.' . $extension;
        $request->file('file')->move($dir, $filename);
        return $filename;
    }

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


How to test? open your browser and type http://localhost/test_laravel/public/tutorial/upload-image-file. You will see this screen
 

3 comments:

Rahul Khandelwal said...

Nice...post

Senghok Eang said...

thank you

Azim Khan said...

This post really helped me one thing need to be done with this add a text field with so that we can post the data.