我已经设置了一个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
问题是,我根本无法从控制器与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 9和flysystem-AWS-S3-v33.0,如果这有帮助的话。
发布于 2022-03-19 19:56:28
我终于找到了连接不起作用的原因。.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变量,并将值保留为空。因此,我的环境变量被这些空变量覆盖,导致连接失败。我想这里要吸取的教训是,如果包含多个具有相同密钥的vars,则始终检查整个.env文件。
奖金
在使用Laravel设置S3之后,您可以使用这些片段来:
$imageName = preg_replace('/[\W]/', '', base64_encode(random_bytes(18)));
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()
$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}}">
if (Storage::disk('s3')->exists($imagePath)) { //make sure to include the full path to the image file in $imagePath
//do stuff
}
Storage::disk('s3')->delete($imagePath);
发布于 2022-03-10 18:39:57
看来你一切都做对了!.它在local
驱动器上工作吗?
此外,您还可以尝试刷新缓存:
php artisan cache:clear
php artisan config:clear
https://stackoverflow.com/questions/71428351
复制相似问题