1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <?php use Illuminate\Http\RedirectResponse; class FilesController { /** * Let the user download the file directly from S3. * * This prevents that large files are piped through webapp's PHP process. * * @link https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.S3Client.html#_createPresignedRequest */ protected function getRedirectFileResponse(string $diskName, string $path): RedirectResponse { $disk = Storage::disk($diskName); if (!$disk->has($path)) { abort(Response::HTTP_NOT_FOUND, 'File does not exist'); } /* @var \League\Flysystem\AwsS3v3\AwsS3Adapter $s3Adapter */ $s3Adapter = $disk->getDriver()->getAdapter(); /* @var \Aws\S3\S3Client $s3Client */ $s3Client = $s3Adapter->getClient(); $reqOptions = [ 'Bucket' => $s3Adapter->getBucket(), 'Key' => $s3Adapter->applyPathPrefix($path), ]; $command = $s3Client->getCommand('GetObject', $reqOptions); $expiration = new \DateTime('+1 day'); $request = $s3Client->createPresignedRequest($command, $expiration); $signedUrl = (string) $request->getUri(); //return a cachable temporary redirect return redirect()->to($signedUrl, 307) ->setPublic() ->setExpires($expiration); } } |