0

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);
Gusti
  • 69
  • 3
  • 11
  • `I have an error` - what error? `because the controller can not read the upload file` - how do you know, what happens? Be specific. https://stackoverflow.com/questions/how-to-ask – Don't Panic May 11 '20 at 07:18
  • i dont kow , when i using debugger F12 in chrome the error say " Call to a member function getClientOriginalExtension() on null" – Gusti May 11 '20 at 13:53
  • You can't do file uploads in AJAX with just `serialize()`. You'll need to use `FormData`, or another approach. There are many duplicates here on SO, [here's a good one](https://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax). – Don't Panic May 12 '20 at 23:54
  • Does this answer your question? [Uploading both data and files in one form using Ajax?](https://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax) – Don't Panic May 12 '20 at 23:55

2 Answers2

0
<form name="data-form" id="data-form" enctype="multipart/form-data">
   {{ csrf_field() }}
   <input type="file" name="img_thumbnail" class="form-control">
</form>

<script src=
    "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

<script type="text/javascript">
    $(document).ready( function () {
       $("form#data-form").on("submit",function (e) {
           e.preventDefault();
           var formData = new FormData(this);
           //Ajax functionality here
           $.ajax({
            url : '{{route('blog.store')}}',
            type : "post",
            data : formData,
            dataType : 'json',
            success:function (data) {
                console.log(data);
                if(data.errors) {
               }
                if(data.success) {
                }
                $('#saveBtn').html('Save Data');
                $('#saveBtn').attr('disabled',false);
            }, // success end
            contentType: false,
            processData: false
        }); // ajax end
    }); // form submit end
}); //document end
0

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;
    }
}

Ahmed Eid
  • 192
  • 1
  • 8