Skip to content
Advertisement

How to fix upload image to s3 using Laravel

I try to upload an image to s3 using Laravel but I receive a runtime error. Using Laravel 5.8, PHP7 and API REST with Postman I send by body base64 I receive an image base64 and I must to upload to s3 and get the request URL.

public function store(Request $request)
{
    $s3Client = new S3Client([
        'region' => 'us-east-2',
        'version' => 'latest',
        'credentials' => [
            'key' => $key,
            'secret' => $secret
        ]
    ]);
    $base64_str = substr($input['base64'], strpos($input['base64'], ",") + 1);
    $image = base64_decode($base64_str);

    $result = $s3Client->putObject([
        'Bucket' => 's3-galgun',
        'Key' => 'saraza.jpg',
        'SourceFile' => $image
    ]);

    return $this->sendResponse($result['ObjectURL'], 'message.', 'ObjectURL');
}

Says:

RuntimeException: Unable to open u�Z�f�{��zڱ��� …….

Advertisement

Answer

Instead of SourceFile you have to use Body. SourceFile is a path to a file, but you do not have a file, you have a base64 encoded source of img. That is why you need to use Body which can be a string. More here: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putobject

Fixed version:

public function store(Request $request)
{
    $s3Client = new S3Client([
        'region' => 'us-east-2',
        'version' => 'latest',
        'credentials' => [
            'key' => $key,
            'secret' => $secret
        ]
    ]);
    $base64_str = substr($input['base64'], strpos($input['base64'], ",") + 1);
    $image = base64_decode($base64_str);

    $result = $s3Client->putObject([
        'Bucket' => 's3-galgun',
        'Key' => 'saraza.jpg',
        'Body' => $image
    ]);

    return $this->sendResponse($result['ObjectURL'], 'message.', 'ObjectURL');
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement