Issue with Laravel File Upload From Ajax Request

  file-upload, javascript, laravel, php

Error Received

exception: "ErrorException"
file: "/var/www/website/app/Http/Controllers/APIV2.php"
line: 1909
message: "file_get_contents(/var/www/website/upload/awBr8Qx_460svvp9_1614090495.webm): failed to open stream: No such file or directory"
trace: [{function: "handleError", class: "IlluminateFoundationBootstrapHandleExceptions", type: "->"},…]

Server Code

public function FileUpload(Request $request){
        $file = $request->file();
        $filenameWithExt = $file->getClientOriginalName();
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        $extension = $file->getClientOriginalExtension();
        $fileNameToStore = $filename.'_'.time().'.'.$extension;
        $path = $file->storeAs('/var/www/website/upload', $fileNameToStore);
        dd(file_get_content($path));
        $name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
        return response()->json([
            'error' => false,
            'success' => true,
            'message' => "Upload Successful"
        ]);
    }

Client Code

let file = document.getElementById('FileField').files[0];
var formData = new FormData();
formData.append('file', file, file.name);
$.ajax({
    url: 'url_here',
    type: 'POST',
    data: formData,
    enctype: 'multipart/form-data',
    processData: false,
    contentType: false,
    success: function(result){/* Handle Success */},
    error: function(data){/* Handle Error */}
});

Source: Laravel

Leave a Reply