如何使用eloquent将图像文件内容保存到SQL数据库中?

时间:2022-09-05 21:21:30

I'm getting confused about how to save an image content inside of a database table.

我对如何在数据库表中保存图像内容感到困惑。

Please see the fourth line of code. I'm sure that this restful method (using POST) is working because getSize() returns the true value.

请参阅第四行代码。我确信这个restful方法(使用POST)正常工作,因为getSize()返回true值。

Also, if I debug what returns the 5th line I get something like the next one:

另外,如果我调试返回第5行的内容,我会得到类似下一行的内容:

如何使用eloquent将图像文件内容保存到SQL数据库中?

So, I'm not sure if what am I missing to save this data into the database.

所以,我不确定我是否缺少将这些数据保存到数据库中。

        $personId = Input::get('PersonId');
        $file = Input::file('media');
        $tmppath = $file->getRealPath();
        $content = file_get_contents($tmppath); //$file->getSize();

        // return $content;

        $model = Person::find($personId);
        $model->Photo = $content;
        $model->save();

        $result = array(
            "success" => true,
            "data" => $personId,
            "error" => ""
        );

1 个解决方案

#1


0  

You need to save the file to the server and only store the path in the database.

您需要将文件保存到服务器,并仅将路径存储在数据库中。

Write an appropriate method, ideally you can store it in a trait.

写一个合适的方法,理想情况下你可以将它存储在一个特征中。

private function saveFileToDisk($file, $fileName)
{
    $path = public_path() . '/uploads/';

    return $file->move($path, $fileName . $file->getClientOriginalExtension());
}

An then pass the file input to your method and provide a name for the file:

然后将文件输入传递给您的方法并提供该文件的名称:

$model->Photo = $this->saveFileToDisk(Input::file('media'), $model->Name);

Obvisouly you need to validate you input before all this.

显然,您需要在所有这些之前验证您的输入。

#1


0  

You need to save the file to the server and only store the path in the database.

您需要将文件保存到服务器,并仅将路径存储在数据库中。

Write an appropriate method, ideally you can store it in a trait.

写一个合适的方法,理想情况下你可以将它存储在一个特征中。

private function saveFileToDisk($file, $fileName)
{
    $path = public_path() . '/uploads/';

    return $file->move($path, $fileName . $file->getClientOriginalExtension());
}

An then pass the file input to your method and provide a name for the file:

然后将文件输入传递给您的方法并提供该文件的名称:

$model->Photo = $this->saveFileToDisk(Input::file('media'), $model->Name);

Obvisouly you need to validate you input before all this.

显然,您需要在所有这些之前验证您的输入。