dr24's avatar
Level 2

Problem with uploading image to Amazon S3 server with Laravel

I am trying to upload image to amazon s3 web server and when I try and upload I get error like this

{"error":{"message":"Error executing \"ListObjects\" on \ AWS HTTP error: Client error: `GET https: The specified bucket is not valid

When I change my disk to be public it uploads correctly in public folder, but when I change it to s3 then this error shows. My .env bucket name and bucket on s3 are the same I checked. Any help is appreciated. Here is my code.

.env

AWS_ACCESS_KEY_ID=somekeyid
AWS_SECRET_ACCESS_KEY=somekey
AWS_DEFAULT_REGION=eu-central-1
AWS_BUCKET=https://awsq-s3.s3.eu-central-1.amazonaws.com

ImageService.php

class ImageService
{
    protected $disk;

    public function __construct(ImageRepository $repository, $disk = 's3')
    {
        $this->disk = $disk;
        parent::__construct($repository);
    }

    public function uploadImages(Model $model, Request $request)
    {
        try {
            DB::beginTransaction();

            $path = "data/" . $model->getTable() . "/" . $model->id;

            if (!$request->has('images')) {
                throw new \Exception("Request must contain images field.");
            }

            $images = $request->get('images');

            if (!is_array($images)) {
                $images = array($images);
            }
            foreach ($images as $image) {
                if (!file_exists($image)) {
                    continue;
                }

                $filename = Str::slug(pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME)) . time();
                $extension = pathinfo($image->getClientOriginalName(), PATHINFO_EXTENSION);
                $fullImageName = $filename . '.' . $extension;
                $storedImagePath = Storage::disk($this->disk)->putFileAs($path, $image, $fullImageName);
                Storage::disk($this->disk)->setVisibility($storedImagePath, 'public');

                $imageModel = new Image();
                $imageModel->name = $fullImageName;
                $imageModel->path = $path;
                $imageModel->full_path = Storage::disk($this->disk)->url($storedImagePath);
                $imageModel->disk = $this->disk;

                $model->images()->save($imageModel);

            }

            DB::commit();

            return $model;

        } catch (\Exception $exception) {
            DB::rollBack();
            throw new \Exception($exception);
        }
    }
}
0 likes
0 replies

Please or to participate in this conversation.