Spec's avatar
Level 2

[L5.3] File Upload issue with Ajax/jQuery

Hey Folks, I got an issue when I want to make a fileUpload with Ajax. I got all running, but my Request instance is allways null.

Here a small snippet from my Action:

public function addPhoto(Request $request)
    {
        return dd($request->file); // Is allways empty when I use it with AJAX
        return  dd(Illuminate\Support\Facades\Input::all()); // This works fine with Ajax, but I want to use $request ;)
    }

My Request instance is allways NULL, that makes me crazy. Input::all() has all data, but I found it a bit messi. I want to use the $request to build something like this: $request->file('photo')->store( ) etc. Maybe anyone of you know what I'm doing wrong.

0 likes
4 replies
dlook's avatar

Do you have enctype='multipart/form-data' or if using collective Form facade 'files' => true?

1 like
Spec's avatar
Level 2

Here is my blade and JS part:

<form action="{{route('imageupload')}}" method="post" enctype="multipart/form-data">
  {{ csrf_field() }}

    <input name="photo" type="file" id="dataForm"/>

  <button type="button" class="btn btn-default" id="sendPhoto">Ajax Upload</button>
  <input type="submit" value="classic upload">
</form>
 $('#sendPhoto').click(function(){

        var formData = new FormData();
        formData.append('photo', $('#dataForm')[0]);
        formData.append('_token', $('input[name="_token"]').val());

        $.ajax({
          type: "POST",
          url:  "interface/fileupload",
          data: formData,
          cache: false,
          contentType: false,
          processData: false
        }).done(function(html){
            $( ".result" ).append( html );
        });    
    });

I don't use collective

dlook's avatar

Try $request->file('name') <- name being the name="" of the input.

Spec's avatar
Level 2

Yeah the same here(->file('photo')), is NULL. The data are there, as input::all() give me the results. But not in the request instance.

Please or to participate in this conversation.