CakePHP中間件:實作檔案上傳和下載功能

王林
發布: 2023-07-30 15:10:01
原創
1418 人瀏覽過

CakePHP中介軟體:實作檔案上傳和下載功能

隨著網路的發展,檔案上傳和下載功能越來越常見。在開發網頁應用程式時,我們經常需要實作檔案上傳和下載。而在使用CakePHP框架開發應用程式時,中間件是一個非常有用的工具,可以幫助我們簡化程式碼並實作檔案上傳和下載功能。接下來,我將介紹如何使用CakePHP中介軟體來實現檔案上傳和下載功能。

首先,我們需要建立一個新的中間件類,在src/Middleware目錄下建立一個名為FileHandlerMiddleware.php的文件,並新增以下程式碼:

<?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);
    }
}
登入後複製

在上述程式碼中,FileHandlerMiddleware是一個用於檔案上傳和下載的中介軟體類別。當收到POST請求並且請求中包含名為file的資料時,中間件將把檔案儲存到uploads資料夾下,並傳回一個成功的JSON回應。當收到帶有file參數的請求時,中間件將依照檔案名稱傳回檔案內容作為回應。

接下來,我們需要將中間件註冊到應用程式中。開啟src/Application.php文件,並在Application類別的middleware方法中註冊中間件。程式碼如下:

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;
}
登入後複製

在上述程式碼中,我們使用add方法將FileHandlerMiddleware中介軟體註冊到中介軟體佇列中。使用中間件佇列可以依序處理多個中間件,並且在執行控制器動作之前執行註冊的中間件。

現在,我們可以使用檔案上傳和下載功能了。假設我們有一個控制器方法來處理檔案上傳:

public function upload()
{
    // 显示上传表单
}
登入後複製

然後,在對應的檢視檔案中新增如下的表單程式碼:

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

在上述程式碼中,我們建立了一個表單,其中包含一個文件上傳欄位和一個提交按鈕。表單的enctype屬性設定為multipart/form-data,這是檔案上傳所必需的。

當使用者選擇檔案並點擊提交按鈕時,檔案將被上傳到伺服器,並傳回一個成功的JSON回應。

另外,我們還可以使用以下URL來下載文件:

/download/{file_name}
登入後複製

例如,要下載名為example.jpg的文件,可以使用以下URL:

/download/example.jpg
登入後複製

檔案將以下載的格式傳回給使用者。

總結:

本文介紹如何使用CakePHP中間件來實現檔案上傳和下載功能。透過建立一個新的中間件類,我們可以處理文件上傳和下載請求,並返回相應的回應。中間件可幫助我們簡化程式碼並增強應用程式的功能。希望本文對你了解並使用CakePHP中間件有所幫助。

以上是CakePHP中間件:實作檔案上傳和下載功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!