loadComponent('RequestHandler'); // Allow JSON request handling } public function add() { $this->request->allowMethod(['post']); // Only allow POST requests // Check if a file is uploaded if (!$this->request->getData('file')) { throw new BadRequestException(__('No file uploaded')); } $file = $this->request->getData('file'); // Basic file validation (you can add more checks here) if ($file->getError() !== UPLOAD_ERR_OK) { throw new InternalErrorException(__('File upload failed')); } // Generate a new filename $filename = time() . '-' . $file->getClientFilename(); // Define the target directory $targetPath = WWW_ROOT . 'files' . DS; // Ensure the directory exists $folder = new Folder($targetPath, true, 0755); // Move the file to the target directory $file->moveTo($targetPath . $filename); // Save the file details in the database (if applicable) $fileEntity = $this->Files->newEmptyEntity(); $fileEntity->filename = $filename; $fileEntity->filepath = 'files/' . $filename; // The relative path to the file if ($this->Files->save($fileEntity)) { return $this->response->withType('application/json') ->withStringBody(json_encode(['status' => 'success', 'filename' => $filename])); } else { throw new InternalErrorException(__('Unable to save file details')); } } }