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);
}