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.

php Courses
php Courses
php Courses
Implementing File Upload and Download with CakePHP Middleware

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.

<?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 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 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

middlewarefile uploadPHPFile DownloadCakePHP
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.