Last active
May 6, 2023 21:37
-
-
Save atakde/cdd67b1694145e54bffd4ca4b78dfa83 to your computer and use it in GitHub Desktop.
Image & File Upload To Digital Ocean Space With PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| use Aws\S3\S3Client; | |
| use Symfony\Component\HttpFoundation\Request; | |
| // settings | |
| $client = new S3Client([ | |
| 'version' => 'latest', | |
| 'region' => '{REGION}', | |
| 'endpoint' => 'https://{REGION}.digitaloceanspaces.com', | |
| 'use_path_style_endpoint' => false, | |
| 'credentials' => [ | |
| 'key' => '{YOUR_KEY}', | |
| 'secret' => '{YOUR_SECRET}', | |
| ], | |
| ]); | |
| // It is related about HttpFoundation package | |
| // You can imagine like $_POST['image'] | |
| $request = Request::createFromGlobals(); | |
| $image = $request->get('image'); | |
| $type = explode(';', $image)[0]; | |
| $type = explode('/', $type)[1]; | |
| // allow only png, jpg, jpeg | |
| if (!in_array($type, ['png', 'jpg', 'jpeg'])) { | |
| return new JsonResponse([ | |
| 'status' => 400, | |
| 'message' => 'Only png, jpg, jpeg files are allowed.' | |
| ], 400); | |
| } | |
| // replace data:image/png;base64, with nothing | |
| $image = str_replace('data:image/' . $type . ';base64,', '', $image); | |
| $image = str_replace(' ', '+', $image); | |
| $data = base64_decode($image); | |
| //upload the image to the server base64 | |
| $result = $client->putObject([ | |
| 'Bucket' => '{BUCKET_NAME}, | |
| 'Key' => uniqid() . '.' . $type, | |
| 'Body' => $data, | |
| 'ACL' => 'public-read', | |
| 'ContentType' => 'image/' . $type, | |
| 'ContentEncoding' => 'base64' | |
| ]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment