Laravel - How to capture Ajax Request Payload Data?

1.1k Views Asked by At

Not a Duplicate Question!!!


Here is my code, using Laravel 5.4.


Form in .blade.php file:

<form id="read-data-form" name="form" method="post" enctype="multipart/form-data" class="form-horizontal">
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <input name="comCode" id="comCode" type="hidden" value=""/>
                <label><span class="text-danger">*</span> Upload File :</label>
                <input name="file" id="fileToUpload" type="file" accept="text/*" />
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6"></div>
        <div class="col-md-6 ">
            <div class="text-right">
                <button type="submit" class="btn operations-btn btn-default" id="upload">Upload</button>
                <button type="button" class="btn operations-btn btn-default" id="stop">Stop</button>
            </div>
        </div>
    </div>
</form>

Ajax-request in .js file:

$("form #read-data-form").submit(function(e) {
    e.preventDefault();  

    var formData = new FormData(this);

    var promise = $.ajax({
        url: 'read_data/file/check',
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        encode: true
    });
    promise.done(function(response){
    });
    promise.fail(function(error){
    });
    promise.always(function(){
    });
}

Browser Console > Network > Headers > Request Payload:

enter image description here

Route in web.php file:

Route::post('read_data/file/check', 'ReadDataController@checkFile');

checkFile() method in ReadDataController.php file:

public function checkFile(Request $request)
{
    $comCode = trim($request->comCode);

    $file = $request->file('file');
    dd($file);
} 

Browser Console > Network > Preview > Request Payload:

This is how output of dd().
enter image description here


Issue:

File could not be captured as in a normal 'multipart/form-data' form without ajax request.

1

There are 1 best solutions below

0
On BEST ANSWER

OK. Finally, I have a solution which is given by a senior person.


Removed this code:

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

Added the following codes:

$uploadDirPath = 'C:/uploaded_files/';
$uploadFile = "moved_uploded_file.txt";

$request->file('file')->move($uploadDirPath, $uploadFile);
$uploaded_file = $uploadDirPath.$uploadFile;