phplaravelamazon-s3

Trying to get a S3 image URL inside a bucket folder


I'm trying to get a proper link to be consumed from an API request. I stored an image in a S3 bucket. Here's the steps:

  1. A user fills a form and upload an image.
  2. Image uploaded into S3 bucket within a folder (let's say: images/mynewimage.png)
  3. The user open a new page which contains the image

The problem is, the image URL I get from Laravel is different from the S3 bucket itself.

From S3 bucket, the url looks like this :

https://prismahrbucket.s3-ap-southeast-1.amazonaws.com/reimburses/Screen+Shot+2020-03-17+at+14.21.38.png

But from Laravel, the given URL is wrong. Like this:

https://prismahrbucket.s3-ap-southeast-1.amazonaws.com/Screen+Shot+2020-03-17+at+14.21.38.png

Please have a look at my scripts:

ReimburseController.php

/**
 * Store a newly created resource in storage.
 *
 * @param  \App\Http\Requests\RequestReimburse  $request
 * @return \Illuminate\Http\Response
 */
public function store(RequestReimburse $request)
{
    $validated = collect($request->validated())
        ->except(['images'])
        ->toArray();

    if ($request->images) {
        $images = json_decode($request->images);
        $paths = [];

        foreach ($images as $image) {
            array_push($paths, $this->handleUploads($image, $validated));
        }

        $validated = array_add($validated, 'images', json_encode($paths));
    }

    $reimburse = Reimburse::create($validated);

    return response()->json([
        'created' => true,
        'data' => $reimburse,
    ], 201);
}


protected function handleUploads($image, $validated)
{
    $imageName = time() . str_random(10) . '.png';

    Storage::disk('s3')
        ->put("reimburses/{$imageName}", base64_decode($image), 'public');

    $path = Storage::disk('s3')->url($imageName);

    return $path;
}

filesystem.php

's3' => [
    'driver' => 's3',
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
    'bucket' => env('AWS_BUCKET'),
    'url' => env('AWS_URL'),
    'visibility' => 'public' // Make s3 files public
],

How can I solve it?


Solution

  • I've just found a solution. Instead of using only $imageName, I specified the folder name at the beginning.

    I mean, I changed this: $path = Storage::disk('s3')->url($imageName);

    To this: $path = Storage::disk('s3')->url("images/$imageName");