Home  >  Article  >  Backend Development  >  CakePHP middleware: implement file upload and download functions

CakePHP middleware: implement file upload and download functions

王林
王林Original
2023-07-30 15:09:251455browse

CakePHP middleware: Implementing file upload and download functions

With the development of the Internet, file upload and download functions are becoming more and more common. When developing web applications, we often need to implement file upload and download. When developing applications using the CakePHP framework, middleware is a very useful tool that can help us simplify the code and implement file upload and download functions. Next, I will introduce how to use CakePHP middleware to implement file upload and download functions.

First, we need to create a new middleware class, create a file 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;
        
        // 处理文件上传
        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;
        }
        
        // 处理文件下载
        $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);
    }
}

In the above code, FileHandlerMiddleware is a middleware class for file upload and download. When a POST request is received and the request contains data named file, the middleware will save the file to the uploads folder and return a success JSON response. When a request with the file parameter is received, the middleware will return the file content according to the file name as a response.

Next, we need to register the middleware into the application. Open the src/Application.php file and register the middleware in the middleware method of the Application class. The code is as follows:

use AppMiddlewareFileHandlerMiddleware;

// ...

public function middleware($middlewareQueue)
{
    $middlewareQueue
        ->add(new FileHandlerMiddleware())
        // 其它中间件
        // ...
        ->add(new ErrorHandlerMiddleware(Configure::read('Error')))
        ->add(new AssetMiddleware())
        ->add(new RoutingMiddleware($this));

    return $middlewareQueue;
}

In the above code, we use the add method to register the FileHandlerMiddleware middleware into the middleware queue. Use a middleware queue to process multiple middlewares in sequence and execute registered middlewares before executing controller actions.

Now, we can use the file upload and download functions. Suppose we have a controller method to handle file upload:

public function upload()
{
    // 显示上传表单
}

Then, add the following form code to the corresponding view file:

<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button type="submit">上传</button>
</form>

In the above code, we create a form , which contains a file upload field and a submit button. The form's enctype attribute is set to multipart/form-data, which is required for file uploads.

When the user selects a file and clicks the submit button, the file will be uploaded to the server and a successful JSON response will be returned.

In addition, we can also use the following URL to download files:

/download/{file_name}

For example, to download a file named example.jpg, you can use the following URL:

/download/example.jpg

The file will be returned to the user in downloaded format.

Summary:

This article introduces how to use CakePHP middleware to implement file upload and download functions. By creating a new middleware class, we can handle file upload and download requests and return appropriate responses. Middleware helps us simplify the code and enhance the functionality of the application. I hope this article will help you understand and use CakePHP middleware.

The above is the detailed content of CakePHP middleware: implement file upload and download functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn