codovel

We no longer support this blog. Please visit this site instead. https://laravelprojectlab.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
 

6 comments:

Rahul Khandelwal said...

Nice...post

BudgetFlyStay said...

thank you

Anonymous 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.

oliver said...

To create a file upload form in laravel you also need to create migrations first. You haven't created migration in your tutorial. Go to the database/migration folder and open the migration file for item. You will see the default structure that include id , name, timestamps.

Source: Laravel file upload form

Anonymous said...

Akan tetapi Admin akan memberi anda beberapa Panduan Supaya anda pemain judi online dapat menang judi online disitus terpecaya anda beberapa ratus juta rupiah
asikqq
dewaqq
sumoqq
interqq
pionpoker
bandar ceme terpercaya
hobiqq
paito warna
forum prediksi

jeslynwang said...


Nagaqq Yang Merupakan Agen Bandarq, Domino 99, Dan Bandar Poker Online Terpercaya di asia hadir untuk anda semua dengan permainan permainan menarik dan bonus menarik untuk anda semua

Bonus yang diberikan NagaQQ :
* Bonus rollingan 0.5%,setiap senin di bagikannya
* Bonus Refferal 10% + 10%,seumur hidup
* Bonus Jackpot, yang dapat anda dapatkan dengan mudah
* Minimal Depo 15.000
* Minimal WD 20.000
* Deposit via Pulsa TELKOMSEL
* 6 JENIS BANK ( BCA , BNI, BRI , MANDIRI , CIMB , DANAMON )

Memegang Gelar atau title sebagai AGEN POKER ONLINE Terbaik di masanya

Games Yang di Hadirkan NagaQQ :
* Poker Online
* BandarQ
* Domino99
* Bandar Poker
* Bandar66
* Sakong
* Capsa Susun
* AduQ
* Perang Bacarrat
* Perang Dadu (New Game)


Info Lebih lanjut Kunjungi :
Website : NAGAQQ
Facebook : NagaQQ official
WHATSAPP : +855977509035
Line : Cs_nagaQQ
TELEGRAM :+855967014811

BACA JUGA BLOGSPORT KAMI YANG LAIN:
Winner NagaQQ
Daftar NagaQQ
nagaqq