{"id":8611,"date":"2019-09-20T19:08:34","date_gmt":"2019-09-20T19:08:34","guid":{"rendered":"https:\/\/alexrusin.com\/?p=8611"},"modified":"2019-09-20T19:12:05","modified_gmt":"2019-09-20T19:12:05","slug":"stream-files-from-s3","status":"publish","type":"post","link":"https:\/\/blog.alexrusin.com\/stream-files-from-s3\/","title":{"rendered":"Stream Files From S3"},"content":{"rendered":"\n
When using S3 as our external storage, sometimes we have to let users download files from S3. If file is too large, it may not fit in the memory. The solution is to stream file into user’s browser straight from S3. Let’s take a look how to do it with Laravel’s Filesystem.<\/p>\n\n\n\n
$path = 'path\/to\/my\/report.csv'\n$adapter = Storage::getAdapter();\n$client = $adapter->getClient();\n$client->registerStreamWrapper();\n\n$object = $client->headObject([\n 'Bucket' => $adapter->getBucket(),\n 'Key' => $path,\n]);\n\n$fileName = basename($path);\n\n$headers = [\n 'Last-Modified' => $object['LastModified'],\n 'Accept-Ranges' => $object['AcceptRanges'],\n 'Content-Length' => $object['ContentLength'],\n 'Content-type' => 'text\/csv',\n 'Content-Disposition' => 'attachment; filename='. $fileName,\n];\n\n\nreturn response()->stream(function () use ($adapter, $export) {\n if ($stream = fopen(\"s3:\/\/{$adapter->getBucket()}\/\". $path, 'r')) {\n while (!feof($stream)) {\n echo fread($stream, 1024);\n }\n fclose($stream);\n } \n}, 200, $headers);<\/pre>\n\n\n\nThere are 2 main things to pay attention to: 1) we need to register s3<\/em> stream wrapper ($client->registerStreamWrapper()) 2) we need to set Content-Disposition <\/em>header to allow user’s browser to force a download.<\/p>\n\n\n\n
The streaming is easy enough to do if you are using plain PHP. Please take a look at the Resources Used links to get an idea how to do that.<\/p>\n\n\n\n
Resources Used<\/h4>\n\n\n\n
https:\/\/aws.amazon.com\/blogs\/developer\/amazon-s3-php-stream-wrapper\/<\/a><\/p>\n\n\n\n