phapi / middleware-file-handler
处理从客户端接收和发送到客户端的文件的中间件
Requires
- php: >=5.6.0
- league/flysystem: 1.*
Requires (Dev)
- mockery/mockery: 0.9.*
- phpunit/phpunit: 4.8.10
- squizlabs/php_codesniffer: 2.*
This package is not auto-updated.
Last update: 2021-02-05 23:00:14 UTC
README
请注意,此包仍在开发中,实现可能会随时更改,文档可能已过时.
文件处理器是一个中间件,用于准备 Phapi 框架以处理客户端的上传和下载文件请求。它类似于修改过的序列化器版本,但没有序列化功能。它注册支持的 MIME 类型,并确保上传的文件类型允许,以及检查上传文件的大小。
该包还包含一个端点,用于处理 PUT(上传文件)和 GET(下载文件)请求。端点依赖于 league/flysystem 来处理与文件存储的交互。
安装
此中间件默认不包括在 Phapi 框架 中,但如果您需要安装它,它可以通过 Packagist 和 Composer 安装。
$ php composer.phar require phapi/middleware-file-handler:1.*
配置
配置可能有点棘手。在 phapi-configuration 仓库 中,所有配置都已按正确的顺序和位置添加。您可以使用此仓库开始新的项目或将其用作更新现有项目的参考。以下是您需要添加到配置中以便使文件处理器中间件工作的列表。
configuration/settings.php
将以下行添加到您的设置文件中(示例)并配置您每个路由的列表和配置
<?php /* * File handler configuration, add an array for each route you want to have. * The file handler requires the FlySystem package, link: http://flysystem.thephpleague.com/ * * Each route has the following configuration options: * 'route', the route itself (don't forget that the route has to be included in the main route table as well) * 'maxFileSize', (optional) the maximum allowed file size * 'mimeTypes', an array with the list of allowed mime types * 'flySystemAdapter', use the adapter that matches your environment */ $container['fileHandlerConfiguration'] = function () { return [ /* Example: [ 'route' => '/user/avatar/{id}/{fileName}', // Complete route 'maxFileSize' => 1024000, // In bytes 'mimeTypes' => [ 'image/gif', 'image/png', 'image/jpg', 'image/jpeg' ], 'flySystemAdapter' => new League\Flysystem\Adapter\Local('/path/to/file/storage/') ]*/ ]; }; // Create the Fly system file system $container['flySystem'] = function ($container) { return new \League\Flysystem\Filesystem( $container['fileHandledConfiguration']['flySystemAdapter'] ); };
configuration/middleware.php
将以下两行添加到您的配置文件中(示例)以将中间件添加到中间件管道
第一行应添加在常规 serializers
之后,必须在 FormatNegotiation
中间件之前添加。
<?php $pipeline->pipe(new \Phapi\Middleware\FileHandler\FileReader($container['fileHandlerConfiguration']));
第二行必须在 Route
和 PostBox
中间件之间添加。
<?php $pipeline->pipe(new \Phapi\Middleware\FileHandler\FileUploader($container['fileHandlerConfiguration']));
configuration/routes.php
最后一步是将新路由添加到您的路由表中(示例)
<?php $routes = [ '/user/avatar/{id}/{fileName}' => '\\Phapi\\Endpoint\\File', ];
使用方法
需要考虑的一些事项
- 确保设置
memory_limit
足够高,以便能够处理大文件。由于我们使用 PUT 方法而不是 POST,上传文件将不会受post_max_size
或upload_max_filesize
的影响。 - 包含的 File 端点期望路由字符串中最后一个变量,该变量将被用作文件名。在上面的示例中,我们有两个变量,id 和文件名,这两个变量都将用于将文件保存到存储中。如果 Flysystem 配置表示文件应保存到
/www/files/
,则文件将保存到/www/files/{id}/{filename}
。 - File 端点将文件保存到指定的位置,仅此而已。因此,一个很好的策略是在 File 端点之前创建一个单独的端点,该端点带有关于文件的信息。该端点应保存信息并返回文件应 PUT 的指定 URL。
Phapi
此中间件是 Phapi 框架中使用的 Phapi 包。中间件也符合 PSR-7 规范,并实现了 Phapi 中间件合同。
许可
Serializer JSON 在 MIT 许可证下授权 - 有关详细信息,请参阅 license.md 文件。
贡献
贡献、错误修复等总是受欢迎的。