【问题标题】:October CMS - API with Upload File十月 CMS - 带有上传文件的 API
【发布时间】:2017-12-27 16:09:47
【问题描述】:

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

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

【问题讨论】:

    标签: php octobercms octobercms-plugins octobercms-backend


    【解决方案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.
    

    如果有什么不清楚的地方请评论。

    【讨论】:

    • 我有这个错误:试图获取非对象的属性,我相信它在这个部分://将该$file附加到模型$yourModel->avatar = $file;跨度>
    • 文件对象好像没有创建,如果有的话可以用$imageData调试一下
    • 我尝试进行调试,但变量 $imageData 的大小非常大,导致 php 出错。
    猜你喜欢
    • 2016-09-11
    • 2017-06-14
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    相关资源
    最近更新 更多