Skip to content

Instantly share code, notes, and snippets.

@treetop1500
Last active January 19, 2022 08:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treetop1500/79993d37b02a5b7b50ca3c30bf5c9fe5 to your computer and use it in GitHub Desktop.
Save treetop1500/79993d37b02a5b7b50ca3c30bf5c9fe5 to your computer and use it in GitHub Desktop.
Amazon S3 Force Download of Remote File with Symfony (AWS S3 PHP SDK V.3)
{
},
"require": {
"aws/aws-sdk-php": "3.*"
}
}
# This file is auto-generated during the composer install
parameters:
...
amazon_key: my_key
amazon_secret: my_secret
amazon_bucket: my_bucket
amazon_region: us-east-1
amazon_version: latest
services:
...
my.amazon.s3:
class: Aws\S3\S3Client
factory_class: Aws\S3\S3Client
factory_method: factory
arguments:
-
credentials: { key: "%amazon_key%", secret: "%amazon_secret%" }
region: "%amazon_region%"
version: "%amazon_version%"
media_download:
path: /media/download/{file}{trailingSlash}
defaults: { _controller: UtilBundle:Download, trailingSlash : "/" }
requirements: { file: "([A-Za-z0-9-._s]+)", trailingSlash : "[/]{0,1}" }
<a href="{{ url('media_download',{'file':entity.path}) }}">
Download
</a>
<?php
namespace UtilBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
public function downloadAction($file)
{
$file_path = "uploads/media/$file"; // path to file once inside bucket
$s3 = $this->get('my.amazon.s3');
$params = array(
'Bucket' => $this->getParameter("amazon_bucket"),
'Key' => $file_path,
'ResponseContentType' => 'application/octet-stream',
'ResponseContentDisposition' => 'attachment; filename="'.$file.'"',
'ResponseCacheControl' => 'No-cache',
);
$command = $s3->getCommand('GetObject',$params);
$preSignedRequest = $s3->createPresignedRequest($command, '+10 minutes');
$body = $preSignedRequest->getUri();
header("Location: ".$body);
die();
return new Response(); // controllers require a response or Symfony will error
}
}
@sunviwo
Copy link

sunviwo commented Nov 11, 2021

Hi, I tried and got the following error:

Service "app.amazon_s3" not found: even though it exists in the app's container, the container inside "App\Controller\AppController" is a smaller service locator that only knows about the "doctrine", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session" and "twig" services. Try using dependency injection instead.

@sunviwo
Copy link

sunviwo commented Nov 11, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment