Iss*_*inu 3 php amazon-s3 amazon-web-services laravel flysystem
我已经设置了一个 S3 存储桶并创建了一个具有完全 S3 访问权限的 IAM 用户,并运行了composer require league/flysystem-aws-s3-v3.
我还在 .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
Run Code Online (Sandbox Code Playgroud)
问题是我根本无法从我的控制器与 S3 交互。我尝试过将文件发送到 S3:
$path = $request->Image->store('images', 's3');
Run Code Online (Sandbox Code Playgroud)
我还手动将图像上传到 S3,然后尝试检查是否可以找到它:
if (Storage::disk('s3')->exists('photo.jpg')) {
dd("file found");
} else{
dd("file not found");
}
Run Code Online (Sandbox Code Playgroud)
这会导致此错误:Unable to check existence for: photo.jpg
这让我认为问题出在flysystem-aws-s3-v3.
有没有办法缩小问题所在的范围?顺便说一句,我正在使用Laravel 9和Flysystem-aws-s3-v3 3.0(如果有帮助的话)。
我终于找到了连接失败的原因。.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=
Run Code Online (Sandbox Code Playgroud)
事实证明,Laravel(或者可能是 Flysystem?)已经配置了相同的 S3 变量并将值保留为空。因此,我的环境变量被这些空变量覆盖,导致连接失败。我想这里要学习的教训是始终检查整个 .env 文件是否包含具有相同密钥的多个变量。
使用 Laravel 设置 S3 后,您可以使用这些片段来:
$imageName = preg_replace('/[\W]/', '', base64_encode(random_bytes(18)));
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
$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}}">
Run Code Online (Sandbox Code Playgroud)
if (Storage::disk('s3')->exists($imagePath)) { //make sure to include the full path to the image file in $imagePath
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
Storage::disk('s3')->delete($imagePath);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7189 次 |
| 最近记录: |