0

我正在使用十月创建一个与我的移动应用程序通信的 API。在这个过程中,我发送一个格式为 base64 的图像,直到这部分没有问题,因为我正在将此 base64 图像转换为 JPG 格式,问题出在将这个 JPG 图像保存在十月的标准流程,即保存 System_Files 文件。

进行此上传的最佳方式是什么?

4

1 回答 1

1

我假设您正在以某种关系保存该文件。

例如:个人资料图片等。(因此在这种情况下,您尝试将该文件附加给用户)

所以以此为例。

在里面user model你可以定义你的关系

public $attachOne = [
    'avatar' => 'System\Models\File'
];

base64现在当从带有编码文件的移动应用程序接收请求时

您提到您已成功转换为,jpeg但例如我也为此添加了粗略的代码。

// we assume you post `base64` string in `img` 
$img = post('img');
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$imageData = base64_decode($img);

// we got raw data of file now we can convert this row data to file in dist and add that to `File` model
$file = (new \System\Models\File)->fromData($imageData, 'your_preferred_name.jpeg');

// attach that $file to Model
$yourModel->avatar = $file;
$yourModel->save();

或者,如果您不使用关系保存该文件,您现在可以指向该文件$file->id并下次找到它或保存以供以后使用。

// next time 
// $file->id
$yourFile = \System\Models\File::find($file->id);

现在您的文件已保存,下次您需要该文件时,您可以直接使用该文件

$imageData = $yourModel->avatar->getContents();
$imageBase64Data = base64_encode($imageData);

// $imageBase64Data <- send to mobile if needed.

如果有任何不清楚的地方,请发表评论。

于 2017-12-28T04:57:41.550 回答