File Uploader
Rhapsody includes a modern, asynchronous file uploader that can handle multiple files and display real-time upload progress. This feature relies on a combination of a JavaScript front-end and a dedicated PHP back-end handler.
Architecture Overview
The progress bar feature is achieved using AJAX. A JavaScript component intercepts the form submission, sends the file(s) to a dedicated API endpoint using XMLHttpRequest, and listens for progress events to update the UI. The PHP back-end simply receives the files and processes them.
1. The Back-End: FileUploader Class
The Rhapsody\Core\FileUploader class is the server-side engine. You can instantiate it in your controller, set rules like allowed MIME types and max file size, and then call the handle() method.
Note: The uploader automatically creates the target directory (storage/uploads/ by default) if it does not exist.
use Rhapsody\Core\FileUploader;
public function handleUpload(Request $request): Response
{
$uploader = new FileUploader();
$uploader->setAllowedMimes(['image/jpeg', 'image/png', 'application/pdf'])
->setMaxSize(5 * 1024 * 1024); // 5 MB
if ($uploader->handle('documents')) {
return $this->json([
'success' => true,
'files' => $uploader->getUploadedFiles()
]);
} else {
return $this->json([
'success' => false,
'errors' => $uploader->getErrors()
], 400);
}
}
2. The Front-End: View & JavaScript
The view contains the HTML form and the JavaScript required to handle the asynchronous upload. The script listens for the form's submit event, creates progress bars, and sends the data.
Key points from the JavaScript implementation in views/upload.twig:
e.preventDefault()– prevents normal full-page submission.FormData– builds a payload that correctly handles file data.XMLHttpRequest– used instead of the Fetch API because XHR has built-inupload.addEventListener('progress', ...)events for real-time progress tracking.- API Endpoint – the JavaScript sends the
FormDatato the route you defined (e.g.,/upload).
You can use the code in views/upload.twig as a complete, working example for your own file upload forms.