imagelaravel-5jquery-file-upload

How to upload image using ajax in laravel


I have a trouble when to upload img using ajax in laravel. I have an error in getClientOriginalExtension() I think that trouble in enctype in ajax because the controller can not read the upload file.

this is my view :

<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script type="text/javascript">
    $(function () {
        $.ajaxSetup({
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
        });
       $('body').on('click', '#saveBtn', function(){
            var url;
            var registerForm = $("#data-form");
            var formData = registerForm.serialize();
            $(this).html('saving...');
            $('#saveBtn').attr('disabled',true);

            $.ajax({
                enctype: 'multipart/form-data',
                url: '{{ route('blog.store') }}',
                type:'POST',
                data:formData,
                success:function(data) {
                    console.log(data);
                    if(data.errors) {
                   }
                    if(data.success) {
                    }
                    $('#saveBtn').html('Save Data');
                    $('#saveBtn').attr('disabled',false);
                },
                error: function (data) {
                  console.log('Error:', data);
                  $('#saveBtn').html('Save Data');
              }

            });
        });
 });
    </script>

and this is my controller

$name_file = time().'.'.$request->img_thumbnail->getClientOriginalExtension();
$request->img_thumbnail->move(public_path('images'), $nama_file);

Solution

  • create.blade.php

    @section('content')
    <form id="submitform">
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" name="name" id="name">
            </div>
    
            <div class="form-group">
                <label for="photo">Photo</label>
                <input type="file" name="photo" id="photo">
            </div>
    
            
            <button class="btn btn-primary" id="submitBtn" type="submit">
                <span class="d-none spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
                <span class="">Submit</span>
            </button>
    
        </form>
    @endsection
    
    @push('custom-scripts')
    <script src="{{ asset('js/upload.js') }}"></script>
    @endpush
    
    

    upload.js

    $(function () {    
        $('#submitBtn').on('click', (e) => {
            e.preventDefault();
            var formData = new FormData();
    
            let name = $("input[name=name]").val();
            let _token = $('meta[name="csrf-token"]').attr('content');
            var photo = $('#photo').prop('files')[0];   
    
            formData.append('photo', photo);
            formData.append('name', name);
            
            $.ajax({
                url: 'api/store',
                type: 'POST',
                contentType: 'multipart/form-data',
                cache: false,
                contentType: false,
                processData: false,
                data: formData,
                success: (response) => {
                    // success
                    console.log(response);
                },
                error: (response) => {
                    console.log(response);
                }
            });
        });
    
    
    });
    
    

    Controller

    class MyController extends Controller
    {
        use StoreImageTrait;
    
        public function store(Request $request)
        {
            $data = $request->all();
            $data['photo'] = $this->verifyAndStoreImage($request, 'photo', 'students');
            Student::create($data);
            return response($data, 200);
        }
    }
    

    StoreImageTrait

    <?php
    
    namespace App\Traits;
    
    use Illuminate\Http\Request;
    
    trait StoreImageTrait
    {
    
        public function verifyAndStoreImage(Request $request, $filename = 'image', $directory = 'unknown')
        {
            if ($request->hasFile($filename)) {
                if (!$request->file($filename)->isValid()) {
                    flash('Invalid image')->error()->important();
                    return redirect()->back()->withInput();
                }
                return $request->file($filename)->store('image/' . $directory, 'public');
            }
            return null;
        }
    }