2017-12-27 217 views
0

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

做这种上传的最佳方法是什么?

回答

1

我假设你用某种关系来保存该文件。

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

所以以此为例。

里面user model你可以从移动应用程序收到请求时与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); 

现在您的文件

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

现在定义你们的关系保存下一次你需要该文件,你可以直接使用该文件

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

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

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

+1

非常感谢支持! – Crazy

+0

我有这个错误:试图获取非对象的属性,我相信它是在这个部分://将该文件附加到Model $ yourModel-> avatar = $ file; – Crazy

+0

似乎没有创建文件对象,可以使用'$ imageData'调试它,如果它存在 –