[使用PUT上传yii2 REST Api文件

问题描述 投票:3回答:2

我正在尝试在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);
php rest yii2
2个回答
2
投票

这是发送带有卷曲的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

0
投票

自版本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');
© www.soinside.com 2019 - 2024. All rights reserved.