大实验室 / yii2-rawfileparser
RawFileParser 是一个 Yii2 扩展,允许您根据 `Content-Type` 头信息解析包含原始文件的请求的内容。它是通过将文件放入 `$_FILES` 数组中来实现的,从而允许您将其作为常规文件上传来处理。
1.0.0
2023-07-05 20:13 UTC
Requires
- yiisoft/yii2: ~2.0.0
This package is auto-updated.
Last update: 2024-09-05 23:15:49 UTC
README
RawFileParser 是一个 Yii2 扩展,允许您根据 Content-Type
头信息解析包含原始文件的请求的内容。它是通过将文件放入 $_FILES
数组中来实现的,从而允许您将其作为常规文件上传来处理。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令
php composer.phar require --prefer-dist daxslab/yii2-rawfileparser "*"
或者在您的 composer.json
文件的 require 部分添加以下内容
"daxslab/yii2-rawfileparser": "*"
配置
为了启用此解析器,您应该按以下方式配置 [[Request::parsers]]
return [ 'components' => [ 'request' => [ 'parsers' => [ 'application/zip' => [ 'class' => 'daxslab\extensions\RawFileParser', 'basename' => 'azipfile' //optional but recommended, the name to locate the file in $_FILES ], 'video/x-matroska' => 'daxslab\extensions\RawFileParser', //basename is not specified, the key $_FILES is a md5 hash of the file content. Ugly, yes... ], ], // ... ], // ... ];
用法
注意:为了使解析器能够工作
- 请求必须将
Content-Type
头信息设置为解析器配置中指定的值 - 必须在尝试访问文件之前调用
Yii::$app->request->getBodyParams()
或Yii::$app->request->post()
,因为此时执行解析器逻辑。
处理上传的文件
Yii::$app->request->getBodyParams(); //parser is executed here, the file is on $_FILES now. $uploadedFile = UploadedFile::getInstanceByName('azipfile'); if (!$uploadedFile) { throw new ServerErrorHttpException(Yii::t('app', 'No file uploaded')); } $uploadedFile->saveAs("/path/to/save/$uploadedFile->name");
由 Daxslab 完成。