yii2使用PUT上传REST Api文件

时间:2014-06-18 00:41:24

标签: 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 :(得分:2)

以下是如何使用curl发送PUT:

curl -X PUT -d 'BLABLABLA' http://localhost/upload

然后在上传控制器中禁用csrf验证:

\yii::$app->request->enableCsrfValidation = false;

以下是使用您的代码的示例上传控制器操作:

public function actionIndex()
{
   \yii::$app->request->enableCsrfValidation = false;
   $putdata = fopen("php://input", "r");
   // make sure that you have /web/upload directory (writeable) 
   // for this to work
   $path = \yii::getAlias('@webroot')."/upload/myputfile.ext";

   $fp = fopen($path, "w");

   while ($data = fread($putdata, 1024))
      fwrite($fp, $data);

   /* Close the streams */
   fclose($fp);
   fclose($putdata);

}

检查上传:

$ cat /path/to/webroot/upload/myputfile.ext
BLABLABLA

答案 1 :(得分:2)

从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');