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?
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.
user model you can defined your relation
public $attachOne = [ 'avatar' => 'System\Models\File' ];
now when receiving request from mobile app with
base64 encoded file
you mentioned you are successfully converting to
jpegbut 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->idand find it next time or save it for later use.
// next time // $file->id $yourFile = \System\Models\File::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.
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?