Implementing File Upload and Download with CakePHP Middleware
This article demonstrates how to create a CakePHP middleware class to handle file uploads and downloads, register it in the application, and use HTML forms and routes to enable users to upload files and retrieve them via a download URL.
With the growth of the internet, file upload and download features are common in web applications. In CakePHP, middleware can simplify implementing these features.
First, create a middleware class FileHandlerMiddleware.php under src/Middleware . The class intercepts POST requests containing a file field, saves the uploaded file to the uploads directory, and returns a JSON success response. It also handles requests with a file parameter by locating the file on disk and streaming it back with appropriate headers for download.
getMethod() === 'POST' && $request->getData('file')) {
$file = $request->getData('file');
$fileName = Text::uuid() . '-' . $file->getClientFilename();
$file->moveTo($path . $fileName);
$response = new Response();
$response = $response->withAddedHeader('Content-Type', 'application/json');
$response->getBody()->write(json_encode(['success' => true, 'message' => '文件上传成功!']));
return $response;
}
// handle download
$params = $request->getAttribute('params');
if (isset($params['file'])) {
$fileName = $params['file'];
$filePath = $path . $fileName;
if (file_exists($filePath)) {
$stream = fopen($filePath, 'r');
$response = new Response();
$response = $response->withAddedHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"');
$response->withBody(new SlimHttpStream($stream));
return $response;
}
}
return $next($request, $response);
}
}
?>Next, register the middleware in src/Application.php by adding it to the middleware queue:
use AppMiddleware\FileHandlerMiddleware;
// ...
public function middleware($middlewareQueue)
{
$middlewareQueue
->add(new FileHandlerMiddleware())
// other middleware
->add(new ErrorHandlerMiddleware(Configure::read('Error')))
->add(new AssetMiddleware())
->add(new RoutingMiddleware($this));
return $middlewareQueue;
}Then create a controller action and a view with an HTML form that uses enctype="multipart/form-data" to allow users to select a file and submit it. Upon submission, the middleware processes the upload and returns a JSON response.
To download a file, request the URL /download/{file_name} , for example /download/example.jpg . The middleware streams the requested file back to the client as a downloadable attachment.
In summary, the article shows how to implement file upload and download in a CakePHP application by writing a custom middleware, registering it, and using simple HTML forms and routes.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.