Implementing File Upload and Download with CakePHP Middleware
This article explains how to create a CakePHP middleware class to handle file upload and download requests, register it in the application, and use a simple HTML form and URL pattern to enable users to upload files and retrieve them via a download endpoint.
With the growth of the Internet, file upload and download features have become commonplace, and web applications often need to implement them. In CakePHP, middleware provides a convenient way to simplify code for handling these operations.
First, create a new middleware class named FileHandlerMiddleware.php in the src/Middleware directory and add the following code:
<?php
namespace AppMiddleware;
use CakeUtilityText;
use CakeHttpResponse;
use PsrHttpMessageResponseInterface;
use PsrHttpMessageServerRequestInterface;
use CakeHttpServerRequest;
class FileHandlerMiddleware
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$path = WWW_ROOT . 'uploads' . DS;
// Handle file upload
if ($request->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 file 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);
}
}The FileHandlerMiddleware class processes POST requests containing a file field by saving the uploaded file to the uploads directory and returning a JSON success response. For requests with a file parameter, it streams the corresponding file back to the client as a download.
Next, register the middleware in the application. Open src/Application.php and add the middleware to the queue in the middleware method:
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;
}By adding FileHandlerMiddleware to the queue, the application processes file upload and download logic before reaching controller actions.
Now create a controller method to display the upload form:
public function upload()
{
// render upload form
}In the corresponding view, add the following HTML form:
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">上传</button>
</form>The form uses multipart/form-data , which is required for file uploads. When a user selects a file and submits the form, the file is uploaded to the server and a JSON response indicating success is returned.
To download a file, use the URL pattern /download/{file_name} . For example, to download example.jpg , request /download/example.jpg . The server will return the file as a downloadable attachment.
In summary, this guide demonstrates how to implement file upload and download functionality in a CakePHP application using a custom middleware class, simplifying the code and enhancing the application's capabilities.
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.