Upload base64 Image using Amazon S3 without storing the image on the local directory with Laravel
2 min readMay 11, 2020
Let’s get into the topic. If you facing problem uploading base64 image using Amazon S3 service this blog is for you. I will also show you without storing the image on your local storage you can upload the image.
- Let’s first show you uploading images on s3 as well as storing locally.
//CONTROLLER
public function upload()
{
$image = $request->image; // the base64 image you want to upload
$slug = time().$this->auth->id; //name prefix
$avatar = $this->imageUpload($image, $slug, base_path('public/avatar/')); Storage::disk('s3')->put('public/avatar/' . $avatar, file_get_contents(base_path('public/avatar/' . $avatar)), 'public');}//upload Logo
private function imageUpload($image, $namePrefix, $destination)
{
list($type, $file) = explode(';', $image);
list(, $extension) = explode('/', $type);
list(, $file) = explode(',', $file);
if (file_exists(base_path('public/avatar/' . $namePrefix . '.' . $extension))) {
chmod(base_path('public/avatar/' . $namePrefix . '.' . $extension), 0777);
unlink(base_path('public/avatar/' . $namePrefix . '.' . $extension));
}
$fileNameToStore = $namePrefix . '.' . $extension;
$source = fopen($image, 'r');
$destination = fopen($destination . $fileNameToStore, 'w');
stream_copy_to_stream($source, $destination);
chmod(base_path('public/avatar/' . $namePrefix . '.' . $extension), 0777);
fclose($source);
fclose($destination);
return $fileNameToStore;
}
2. You may don’t want to save the image locally and upload it to s3. Follow the process below:
//CONTROLLER
public function upload()
{
$image = $request->image; // the base64 image you want to upload
$slug = time().$this->auth->id; //name prefix
$avatar = $this->getFileName($image, $slug); Storage::disk('s3')->put('public/avatar/' . $avatar['name'], base64_decode($avatar['file']), 'public');
}private function getFileName($image, $namePrefix)
{
list($type, $file) = explode(';', $image);
list(, $extension) = explode('/', $type);
list(, $file) = explode(',', $file);
$result['name'] = $namePrefix . '.' . $extension;
$result['file'] = $file;
return $result;
}
I hope this blog will help you. Thank you. :)