Thanks for the help, I have finally managed to get some time to look at this, I still struggle with understanding the whole Uppy thing, but here is how I got what I wanted:
1) Moved file size & extension checks into the try block, throwing exceptions as needed.
Code: Select all
// Allowed file extensions
$allowed = array('txt','csv');
// Maximum file size
$maxfilesize = 5 * 1024 * 1024; // (5 MB)
$filename = nuSanitizeFilename(basename($_FILES['file']['name']));
$target_dir = '/forte/upload/files/';
$target_file = $target_dir . $filename;
$error = nuTranslate('Sorry, there was an error uploading your file.');
try {
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
throw new Exception('Invalid file type .' . $ext);
}
$filesize = $_FILES["file"]["size"];
if ($filesize > $maxfilesize) {
throw new Exception('Maximum file size 5MB exceeded');
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
// Add custom processing here...
$data = ['url' => $target_file, 'file' => $filename, 'message' => 'The file ' . $filename . ' has been uploaded.'];
http_response_code(201);
$result = json_encode($data);
} else {
throw new Exception('Unable to move the uploaded file to its final location:' . $target_file);
}
} catch (Throwable $th) {
$data = ['message' => $error, 'error' => $th->getMessage()];
$result = json_encode($data);
}
2) Used function nuOnFileUploadComplete as above, but with typo fixed(!) and nuMessage to relay error messages to user:
Code: Select all
function nuOnFileUploadComplete(source, id, result) {
if (result.successful.length > 0) {
console.log('Successful:')
result.successful.forEach((file) => {
console.log(file.response.body.message)
})
} else {
if (result.failed.length > 0) {
console.log('Errors:')
result.failed.forEach((file) => {
nuMessage(file.response.body.message + '<br>' + file.response.body.error)
})
}
}
}
It would be cool if I could work out how to get Uppy to display my custom error messages in the upload box rather than just a bland "Upload error", and I suppose it is misleading to have Uppy report an upload failure when actually the file uploaded fine, it just failed a post-upload check.
Any criticisms or suggestion gratefully received!
Neil.