我正在尝试在 Yii2 中添加 REST api 供移动应用程序用来上传图像/音频文件。我试图使用 PUT 方法从 http 表单数据获取图像/文件数据,但由于某种原因 fopen("php://input", "r"); 返回空流。我尝试了此示例中给出的代码http://www.php.net/m...put-method.php。
<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");
/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");
/* Read the data 1 KB at a time
and write to the file */
while ($data = fread($putdata, 1024))
fwrite($fp, $data);
/* Close the streams */
fclose($fp);
fclose($putdata);
?>
Run Code Online (Sandbox Code Playgroud)
同时,使用 POST 方法也可以。使用以下代码进行 POST
$putdata = fopen($_FILES['photo']['tmp_name'], "r");
$filename = $this->documentPath.uniqid().'.jpg';
/* Open a file for writing */
$fp = fopen($filename, "w");
/* Read the data 1 KB at a time
and write to the file */
while ($data = fread($putdata, 1024))
fwrite($fp, $data);
/* Close the streams */
fclose($fp);
fclose($putdata);
Run Code Online (Sandbox Code Playgroud)
从版本 2.0.10 开始,出现了一个内置机制,允许您将 PUT 与 formData 一起使用: https: //www.yiiframework.com/doc/api/2.0/yii-web-multipartformdataparser
所以,首先你需要将解析器添加到配置文件中
return [
'components' => [
'request' => [
'parsers' => [
'multipart/form-data' => 'yii\web\MultipartFormDataParser'
],
],
// ...
],
// ...
];
Run Code Online (Sandbox Code Playgroud)
接下来 - 执行getBodyParams以填充 $_FILES。这应该在请求任何文件之前执行。
$restRequestData = Yii::$app->request->getBodyParams();
Run Code Online (Sandbox Code Playgroud)
然后文件就可以通过通用方法获得:
$file = UploadedFile::getInstancesByName('photo');
Run Code Online (Sandbox Code Playgroud)