Pliki poza aplikacją:
# mkdir -p /var/uploads/my_app # chown www-data:www-data /var/uploads/my_app # chmod 750 /var/uploads/my_app
config/app_local.php
return [
'App' => [
'uploadsDir' => '/var/uploads/my_app',
],
];
Użycie w aplikacji
use Cake\Core\Configure; $uploadsDir = Configure::read('App.uploadsDir'); // Pełna ścieżka do pliku $path = $uploadsDir . DS . strtolower($file->modelname) // projects / companies / .. . DS . $file->project_id // np. 42 . DS . $file->filename; // np. abc123.pdf // Wynik: /var/uploads/app1/projects/42/abc123.pdf
src/Utility/FilePathHelper.php
namespace App\Utility; use Cake\Core\Configure; class FilePathHelper { // Rzeczywista ścieżka do pliku public static function getPath(object $file): string { $base = Configure::read('App.uploadsDir'); $model = strtolower($file->modelname); // projects $contextId = $file->project_id ?? $file->company_id ?? $file->validation_id; return implode(DS, [$base, $model, $contextId, $file->filename]); } // Ścieżka widziana przez usera - wirtualna public static function getUrl(int $fileId): string { return '/files/download/' . $fileId; } }
FilesController::download($id) – bez helpera
public function download($id)
{
$file = $this->Files->get($id);
// Sprawdź uprawnienia użytkownika
// $this->Authentication->getIdentity()->getIdentifier()
if (!$this->Authentication->getIdentity() || !$this->canAccess($file)) {
throw new ForbiddenException();
}
// Bez helpera
$uploadsDir = Configure::read('App.uploadsDir');
$path = $uploadsDir . '/' . $file->dir . '/' . $file->filename;
$this->response = $this->response
->withFile($path, ['download' => true])
->withHeader('Content-Disposition',
'attachment; filename="' . $file->orygname . '"');
return $this->response;
}
Z helperem – nie trzeba składać ścieżki, pobierać uploadDir,
use App\Utility\FilePathHelper; $path = FilePathHelper::getPath($file); // /var/uploads/app1/projects/42/abc123.pdf