【问题标题】:saving a file in php without saving in a folder in yii php将文件保存在php中而不保存在yii php中的文件夹中
【发布时间】:2016-09-19 05:01:57
【问题描述】:

我将文件保存为php 中的long blob,首先将其保存在文件夹中,然后保存到数据库中,问题是服务器具有写入权限,所以我想直接保存它

这是我尝试过的(效果很好):

 if(isset($_POST['image'])){

        $id = 0;

        $image = $_POST['image'];
         $tmp_image = date('YmdHisu').'.jpg';

        file_put_contents($tmp_image, base64_decode($image));

         $sql = "INSERT INTO fingerprint(template)
            VALUES ('".addslashes(file_get_contents($tmp_image))."')";

                try
                    {
                               $connection=Yii::app()->db; 
                                $command=$connection->createCommand($sql);

                                $rowCount=$command->execute(); // execute the non-query SQL


                    echo "saved successifully";
                    unlink($tmp_image);

                    }
                    catch(Exception $ex)
                    {
                        echo 'Query failed' , $ex->getMessage();
                        unlink($tmp_image);
                    }


            }

如何将其保存在 mysql 中的 blob field 中,而无需先将其保存在文件夹中,然后再保存到 db 中

【问题讨论】:

  • 如果$_POST['image']确实包含文件的内容(我怀疑),那么只需addslashes($_POST['image'])
  • $_POST['image'] 包含以 base 64 格式编码的文件字符串,这就是为什么要在上面对其进行解码。以上工作完美
  • 你用的是什么版本的yii?
  • 我使用的是 yii 版本 1
  • 你应该用 yii 标准的方式上传它:创建一个模型来上传你的文件。

标签: php mysql yii


【解决方案1】:

假设您已通过 Android 使用 POST 方法将文件发送到运行 Yii1 的服务器。

首先,物理文件包含在 $_FILES 变量和 $_POST 变量中,正如您所说,包含以 base 64 格式编码的文件字符串(我写这个是为了明确答案)。 $_FILE DOCUMENTATION

现在这是您可以尝试使用 yii 代码以标准 MVC yii 方式上传文件的方法:

您确实是从外部设备上传文件,但 Yii 提供了CUploadedFile Class 的帮助:

调用getInstance 获取上传文件的实例,然后使用saveAs 将其保存在服务器上。您还可以查询文件的其他信息,包括名称、临时名称、类型、大小和错误。

特别是您应该使用函数getInstancesByName,它返回一个以指定数组名称开头的实例数组。

$temp = CUploadedFile::getInstanceByName("image");  // $_FILES['image']

这样您就可以访问文件数据:

$temp->name; // Name of the file
$temp->type; // Type of the file 
$temp->size; // Size of the file
// etc etc..
$temp->saveAs("/your/path/" . $tmp_image . $temp->type); // Save your file

最后,您可以检查文件是否已保存并执行您的查询:

if($temp->saveAs("/your/path/" . $tmp_image . $temp->type)) {
 // File is saved you can execute the query for save the record in your db
} else {
 // Something went wrong.
}

您也可以在模型中转移此逻辑。 check this link for more infos

希望这会对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    相关资源
    最近更新 更多