Can't receive files from JQuery Ajax request in Laravel

Viewed 49

When trying to upload a file CSV / Excel file and receiving it in an ajax request, it's not working as expected.

I used a formdata object to upload the files like such:

      const formData = new FormData()
            formData.append('file', file)
            //upload the file to the server
            Api.makeRequest('uploadFromFile', {
                processData: false,
                contentType: false,
                enctype: 'multipart/form-data',
                cache: false,
                data: formData,
               complete: function (xhr) {
                    if(xhr.status === 201 || xhr.status === 200){
                        console.log(xhr.responseJSON)
                    }else {
                        alert('error')
                        console.error(xhr.responseJSON)
                    }
               }
            })

As I read from the documentation, you have to extract it like such:

$file = $request ->file('file_key')

When using this syntax, I get an error, and Laravel can't extract the file:

    public function uploadFromFile(Request $request){
        if($request->hasFile('file')){
        $file = $request->file('file');
        return $file;
        }else{
            return response()->json(['error' => 'No file uploaded'], 400);
        }

However, it works fine when I use the regular request->has() function. A return type is just an object. What am I doing wrong since I can't get the file in the correct format?


//This works, getting some data but not a proper file object
    public function uploadFromFile(Request $request){
        if($request->has('file')){
        $file = $request->get('file');
        return $file;
        }else{
            return response()->json(['error' => 'No file uploaded'], 400);
        }
1 Answers

<script>
  var droppedFiles='';
  //input file change event to call this function
  function FileUpload(e) 
  {
    droppedFiles = e.target.files || e.dataTransfer.files;
  }
 
  $('#FrmId').on('submit', function (e) {
    var $form = $('#FrmId');
    var $input    = $form.find('input[type="file"]');
    var form_data = new FormData($('#FrmId')[0]);
    if (droppedFiles) 
    {
      $.each( droppedFiles, function(i, file) {
        form_data.append( $input.attr('name'), file );
      });
    }
  
    $.ajax({
          type: "POST",
          enctype: "multipart/form-data",
          url: "url",
          data: form_data,
          contentType: false,
          cache: false,
          processData: false,
        }).done(function (data) {
       
        }).fail(function () {
          
        }); 
        return false;
    });
</script>

Related