【问题标题】:Php Yii2 upload base64 image fails with file_put_contentsPhp Yii2 上传 base64 图像失败并带有 file_put_contents
【发布时间】:2019-09-30 21:49:37
【问题描述】:

我正在接收来自 android 的 base64 编码图像,我想将其上传到 yii2

所以我添加了以下内容

$success = file_put_contents(Yii::getAlias('@web').'/uploads/img.png'
              ,base64_decode($detail));

这里的 $detail 是 base 64 编码的图像

当我尝试上传时出现错误

yii\base\ErrorException: file_put_contents(/uploads/img.png):
  failed to open stream: No such file or directory 

我还需要添加什么才能使上传正常工作,因为大多数结果都显示上述内容

【问题讨论】:

    标签: php file-upload yii2


    【解决方案1】:

    问题出在您使用的别名中。 @web 别名是当前正在运行的应用程序的基本 URL,在您的情况下是一个空字符串。感谢您尝试将上传的文件另存为/uploads/img.png

    您可能想改用@webroot 别名。它指向包含 index.php 文件的目录。

    您可以找到有关预定义别名 here 的更多信息。

    【讨论】:

      【解决方案2】:

      上传文件夹位于 web 文件夹中

      $success = file_put_contents(Yii::getAlias('@web/uploads/img.png'
                    ,base64_decode($detail));
      

      项目的基本路径或

      $success = file_put_contents(Yii::getAlias('@app/uploads/img.png'
                    ,base64_decode($detail)); //base path
      
      $success = file_put_contents(Yii::getAlias('@webroot/uploads/img.png'
                    ,base64_decode($detail)); //root directory(directory containing the entry script.)
      

      更多示例: 在项目的根目录中

      $_SERVER["DOCUMENT_ROOT"].'/uploads/img.png';
      \yii\helpers\Url::to('@webroot/uploads/img.png');
      

      从项目根目录的文件夹中获取文件(代码在另一个文件夹中):

      __DIR__.'\..\uploads\img.png'
      

      【讨论】:

        猜你喜欢
        • 2016-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-17
        • 2014-10-25
        • 2014-07-22
        • 1970-01-01
        相关资源
        最近更新 更多