十月 CMS - API 带上传文件

October CMS - API with Upload File

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

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

我假设您正在保存与某种关系相关的文件。

for ex: profile picture etc.. (so in this case you try to attach that file to user)

所以以此为例

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

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

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

you mentioned you are successfully converting to jpeg but for example I just added rough code for that as well.

// 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();

OR if you don't save that file with relation you can now point that file with $file->id and find it next time or save it for later use.

// 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.

如有不明之处请评论。