我正在寻找一个很好的解决方案来获取亚马逊s3的签名网址。
我有一个使用它的版本,但没有使用laravel:
private function getUrl ()
{
$distribution = $_SERVER["AWS_CDN_URL"];
$cf = Amazon::getCFClient();
$url = $cf->getSignedUrl(array(
'url' => $distribution . self::AWS_PATH.rawurlencode($this->fileName),
'expires' => time() + (session_cache_expire() * 60)));
return $url;
}
我不知道这是否是使用laravel的最佳方式,因为它有一个完整的文件系统可以工作......
但如果没有其他办法,我该如何获得客户?调试我在Filesystem对象中找到了它的一个实例,但它受到保护......
答案 0 :(得分:39)
在Laravel,
$s3 = \Storage::disk('s3');
$client = $s3->getDriver()->getAdapter()->getClient();
$expiry = "+10 minutes";
$command = $client->getCommand('GetObject', [
'Bucket' => \Config::get('filesystems.disks.s3.bucket'),
'Key' => "file/in/s3/bucket"
]);
$request = $client->createPresignedRequest($command, $expiry);
return (string) $request->getUri();
确保您拥有适用于flysystem composer程序包的AWS(版本会有所不同):
"league/flysystem-aws-s3-v3": "1.0.9"
答案 1 :(得分:23)
对于Laravel 5.5及以上版本, 您现在可以使用临时URL / s3预签名URL。
use \Storage;
// Make sure you have s3 as your disk driver
$url = Storage::disk('s3')->temporaryUrl(
'file1.jpg', Carbon::now()->addMinutes(5)
);
这仅适用于s3存储驱动程序AFAIK。
答案 2 :(得分:6)
经过很多错误之后,终于找到了使用以下代码访问s3存储桶私有内容的解决方案:-
use Storage;
use Config;
$client = Storage::disk('s3')->getDriver()->getAdapter()->getClient();
$bucket = Config::get('filesystems.disks.s3.bucket');
$command = $client->getCommand('GetObject', [
'Bucket' => $bucket,
'Key' => '344772707_360.mp4' // file name in s3 bucket which you want to access
]);
$request = $client->createPresignedRequest($command, '+20 minutes');
// Get the actual presigned-url
echo $presignedUrl = (string)$request->getUri();
答案 3 :(得分:4)
上面的解释答案(@brian_d)可以,但是生成预签名的URL需要太多时间。我浪费了将近4-5天来克服它。终于跟随为我工作。感谢@Kenth。
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
$disk = Storage::disk('s3');
$url = $disk->getAwsTemporaryUrl($disk->getDriver()->getAdapter(), $value, Carbon::now()->addMinutes(5), []);
答案 4 :(得分:1)
这是将图像上传到 S3 并创建签名 URL 的完整代码;
首先获取一个文件对象并创建对象名称
$filename = $_FILES["image"]["name"];
$array = explode('.', $filename);
$fileExt = $array[1]; // to get file extension
$objectName = 'images/' . time() .$fileExt; // create object name
$document = fopen($_FILES["image"]["tmp_name"],'r');
// Code to upload document on s3
$s3 = \Storage::disk('s3');
$s3->put($objectName,$document,'public');
// If you want to get uploaded document Url you can use below code:
$image_name = \Storage::disk('s3')->url($name); // it will return stored document url
用于创建/获取签名 URL 的代码,您也可以将其作为单独的函数:
$s3 = \Storage::disk('s3');
$client = $s3->getDriver()->getAdapter()->getClient();
$expiry = "+10 minutes";
$command = $client->getCommand('GetObject', [
'Bucket' => config('params.YOUR_AWS_BUCKET_NAME'), // bucket name
'Key' => $objectName
]);
$request = $client->createPresignedRequest($command, $expiry);
$url = (string) $request->getUri(); // it will return signed URL