php - 使用 PUT 上传 yii2 REST Api 文件

标签 php rest yii2

我正在尝试在 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);
?>

与此同时,使用 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);

最佳答案

从 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'
            ],
        ],
        // ...
    ],
    // ...
];

下一步 - 执行 getBodyParams 来填充 $_FILES。这应该在请求任何文件之前执行。

$restRequestData = Yii::$app->request->getBodyParams();

然后文件可以通过通用方法访问:

$file = UploadedFile::getInstancesByName('photo');

关于php - 使用 PUT 上传 yii2 REST Api 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24275419/

相关文章:

php - 为什么我在 Codeigniter 上收到错误 'Call to undefined function delete_cookie ()'?

php - PDO - 调用非对象上的成员函数 fetch()?

http - 共享 api 响应的 whurl 替代方案

rest - API 基础设施类是否应该成为 DDD 领域的一部分?

mysql - 如何在 yii CDbCriteria 中转换 mysql 子查询?

php - 外键一对多(postgresql、php、yii2)

php - 如何从 PHP 中的 HTTP Accept header 中选择内容类型

php - 在 Laravel 中捕获并保存元素,而不是通过 PrimaryKey

来自路径/路由的 ASP.NET Core API 搜索参数

php - Yii2 - Web 进程不可写目录 |前端/网络/ Assets