Skip to content
Advertisement

October CMS – API with Upload File

I’m using October to create an API that is communicating with my mobile app. In this process I am sending an image that is in the format base64, until this part is not being problem, because I am converting this base64 image to JPG format, the problem is being in the second part that is saving this JPG image in the standard process of October, which is, save the System_Files file.

What is the best way to do this upload?

Advertisement

Answer

I assume that you are saving that file with some relation.

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

so taking that as example.

Inside user model you can defined your relation

public $attachOne = [
    'avatar' => 'SystemModelsFile'
];

now when receiving request from mobile app with base64 encoded file

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 SystemModelsFile)->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 = SystemModelsFile::find($file->id);

now your file is saved next time you need that file you can directly use that file

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

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

if anything is unclear please comment.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement