-3

I am trying to upload a form with jQuery and Ajax using Laravel as server side code, my form is:

HTML:

  <form action="" method="post">
    <div class="form-group">
       <label for="exampleInputEmail1">Comprobante</label>
       <input type="file" name="file" class="form-control" id="file" aria-describedby="emailHelp">
    </div>
   <div class="form-group">
      <label for="exampleInputEmail1">Nombre</label>
       <input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name">
    </div>
 </form>

jQuery, Ajax:

     $( 'body' ).on( "submit", 'form', function() {
        event.preventDefault();

        var formData = new FormData();
        formData.append("file", $('#file')[0].files[0]);
        formData.append("name", $('#name').val());

        var formData = $(this).serialize();

        $.ajax({
            type:'POST',
            url:"{{ url('/accountability/store') }}",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: formData,
            success:function(html)
            {
                alert('stored!');
            }
        });
    });                                                      

Laravel:

  $extension = $request->file('file')->getClientOriginalExtension();

  $filename = $request->rut.'_rendicion_'. date('d_m_Y_h_i_s') .'.'.$extension;

  Storage::disk('dropbox')->putFileAs(
        '/intranet_jisparking_archivos_web/', 
        $request->file('file'),
        $filename
    );

The problem is that it says that

Call to a member function getClientOriginalExtension() on null

But I do not understand why? because I am uploading the file with this $('#file')[0].files[0] in the jQuery. It looks like $request->file('file') is empty, how can I fix it?

Thanks!

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
Emkrypted
  • 59
  • 9
  • 1
    You're setting `var formData = new FormData()` and adding the `append('file', ...)`, then promptly overriding it to `var formData = $(this).serialize();`. Could that be the issue? – Tim Lewis Aug 28 '19 at 16:43
  • [How to upload a file using jQuery.ajax and FormData](https://stackoverflow.com/questions/9622901/how-to-upload-a-file-using-jquery-ajax-and-formdata) – Andreas Aug 28 '19 at 16:46
  • Dont use `var formData = $(this).serialize();` – Mayank Pandeyz Aug 28 '19 at 16:48
  • Try order of execution of statement as below var formData = $(this).serialize(); formData.append("file", $('#file')[0].files[0]); formData.append("name", $('#name').val()); – Ruchita Sheth Aug 28 '19 at 17:16
  • @Ruchi They don't need `serialize()` at all. The answer below demonstrates the correct logic; `new FormData()`, append then send. – Tim Lewis Aug 28 '19 at 17:18

1 Answers1

2

Try this:

var formData = new FormData();
var file = $('#file').prop('files')[0];

formData.append('file', file);
formData.append('other_variable', $('#other_variable').val());
// Don't use serialize here, as it is used when we want to send the data of entire form in a query string way and that will not work for file upload

$.ajax({
    url: '{{ url("your_url") }}',
    method: 'post',
    data: formData,
    contentType : false,
    processData : false,
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    success: function(response){
        // Do what ever you want to do on sucsess
    }
});

In controller method, you will get the file like:

$file = Input::file('file');
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59