簡體   English   中英

Laravel 無法連接到 AWS S3

[英]Laravel can't connect to AWS S3

我已經設置了一個 S3 存儲桶並創建了一個具有完全 S3 訪問權限的 IAM 用戶,並運行了composer require league/flysystem-aws-s3-v3

我還配置了以下 in.env:

AWS_ACCESS_KEY_ID=XXXX
AWS_SECRET_ACCESS_KEY=YYYY
AWS_DEFAULT_REGION=us-west-3
AWS_BUCKET=my-bucket
AWS_USE_PATH_STYLE_ENDPOINT=false
FILESYSTEM_DRIVER=s3

問題是我的 controller 根本無法與 S3 交互。 我嘗試將文件發送到 S3:

$path = $request->Image->store('images', 's3');

我還手動將圖像上傳到 S3,然后嘗試檢查是否可以找到它:

if (Storage::disk('s3')->exists('photo.jpg')) {
dd("file found");
} else{
dd("file not found");
}

這會導致此錯誤: Unable to check existence for: photo.jpg

這讓我認為問題出在flysystem-aws-s3-v3上。

有沒有辦法縮小問題所在? 順便說一句,如果有幫助,我正在使用Laravel 9flysystem-aws-s3-v3 3.0

看起來你做的一切都是正確的。 ..它適用於local驅動器嗎?

您也可以嘗試刷新緩存:

php artisan cache:clear
php artisan config:clear

我終於找到了連接不起作用的原因。 這是 .env 文件的樣子:

//some env vars here...

AWS_ACCESS_KEY_ID=XXXX
AWS_SECRET_ACCESS_KEY=YYYY
AWS_DEFAULT_REGION=us-west-3
AWS_BUCKET=my-bucket
AWS_USE_PATH_STYLE_ENDPOINT=false
FILESYSTEM_DRIVER=s3

//many other env vars here...

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=

事實證明,Laravel(或者可能是 Flysystem?)已經配置了相同的 S3 變量並將值留空。 所以我的環境變量被這些空變量覆蓋,導致連接失敗。 我想這里要學習的課程是始終檢查您的整個.env 文件,如果它包含多個具有相同鍵的變量。

獎金

使用 Laravel 設置 S3 后,您可以使用這些代碼段:

  • 生成一個隨機字符串作為圖像文件的新名稱:
$imageName = preg_replace('/[\W]/', '', base64_encode(random_bytes(18)));
  • 將圖像保存到您的 S3 存儲桶:
Storage::disk('s3')->put($newImagePath, file_get_contents($imageName));
 //$imageName is just a string containing the name of the image file and it's extension, something like 'exampleImage.png'
 //make sure to include the extension of the image in the $imageName, to do that, concatenate your the name of your image with "." + $Image->extension()
  • 從您的 S3 存儲桶中獲取圖像:
$image =  Storage::disk('s3')->temporaryUrl($imagePath, Carbon::now()->addSeconds(40));   //tip: if you get a squiggly line on tempraryUrl(), it's just Intelephense shenanigans, you can just ignore it or remove it using https://github.com/barryvdh/laravel-ide-helper 
//This will generate a temporary link that your Blade file can use to access an image, this link will last for 40 seconds, this 40 seconds is the period when the image link will be accessible.
//Of course after your image loads onto the browser, even if the image link is gone, the image will remain on the page, reloading the page generates a new image link that works for another 40 seconds. 
//This will work even with S3 images stored with Private visibility.

//In your blade file:
<img src="{{$image}}">
  • 檢查您的 S3 存儲桶中是否存在圖像:
if (Storage::disk('s3')->exists($imagePath)) {  //make sure to include the full path to the image file in $imagePath
//do stuff
}
  • 從您的 S3 存儲桶中刪除圖像:
Storage::disk('s3')->delete($imagePath);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM