Home > Back-end >  File upload issue using ajax in laravel 6
File upload issue using ajax in laravel 6

Time:10-01

I am trying to store pdf along with other input value using ajax in laravel 6. Here I did not use form html element . It shows Call to a member function getClientOriginalExtension() on null . How can I send file ?

In Blade

<input name="phone" type="text" >
<input type="file" name="my_doc" accept="application/pdf"  id="my_doc">

<button type="button" > Save </button>

$(document).on('click', '.store_new', function () {
   var phone= $('.phone').val();
   var my_doc= $('.my_doc').val();

   $.ajax({
        url: '{{ url('/admin/add-new-item') }}',
        type: "POST",
        headers: {
             'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        data: {
            phone: phone,
            my_doc: my_doc,
        },
        success: function (response) {
                   
        },
        error: function (jqXHR, textStatus, errorThrown) {

        }
     });
});

In controller

use File;

public function store(Request $request)
{
  
    $image = $request->file('my_doc');
    $new_name = rand() . '.' . $image->getClientOriginalExtension();
    $image->move(public_path('final_doc'), $new_name);

}

CodePudding user response:

you need to send your payload as formData or convert your object to formData and pass the actual file

i.e.

let formData = new FormData()
formData.append('phone', $('.phone').val() )
// Attach file
formData.append('my_doc', $('input[type=file]')[0].files[0])


$.ajax({
    .
    .
    .
    data: formData,
    .
    .
    .
});

or you can use this

Also, on your laravel controller make sure the document is not null before processing it so you won't get any php error.

$doc = $request->file('my_doc');

if ( $doc ) {
    // process your file
}
  • Related