从Amazon S3与Laravel下载文件文件、Amazon、Laravel

2023-09-11 09:14:26 作者:清新长发女▽

我有点不确定,如何启动一个下载的文件从Amazon S3与Laravel 4.我使用AWS

I'm a little sure as to how to launch a download of a file from Amazon S3 with Laravel 4. I'm using the AWS

$result = $s3->getObject(array(
    'Bucket' => $bucket,
    'Key'    => 'data.txt',
));

// temp file
$file = tempnam('../uploads', 'download_');

file_put_contents($file, $result['Body']);

$response = Response::download($file, 'test-file.txt');

//unlink($file);

return $response;

以上的作品,但我只能和本地保存文件。如何使用结果从S3正确地响应::下载()

谢谢!

编辑:我发现我可以使用 $ S3-> getObjectUrl($桶,$文件,​​$过期)来生成访问URL。这可以工作,但它仍然没有解决上述全部问题。

I've found I can use $s3->getObjectUrl($bucket, $file, $expiration) to generate an access URL. This could work, but it still doesn't solve the problem above completely.

EDIT2:

$result = $s3->getObject(array(
    'Bucket' => $bucket,
    'Key'    => 'data.txt',
));

header('Content-type: ' . $result['ContentType']);
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-length:' . $result['ContentLength']);

echo $result['Body'];

仍然不认为这是理想的,有关系吗?

Still don't think it's ideal, though?

推荐答案

的S3Client::getObject()方法允许你指定当发送响应S3应该使用头。该getObjectUrl()法使用GetObject操作生成URL,并且可以接受在其最后一个参数的任何有效GetObject的参数。你应该能够做一个直接的S3到用户下载与做这样的事情使用pre-标识的URL所需的标题:

The S3Client::getObject() method allows you to specify headers that S3 should use when it sends the response. The getObjectUrl() method uses the GetObject operation to generate the URL, and can accept any valid GetObject parameters in its last argument. You should be able to do a direct S3-to-user download with your desired headers using a pre-signed URL by doing something like this:

$downloadUrl = $s3->getObjectUrl($bucket, 'data.txt', '+5 minutes', array(
    'ResponseContentDisposition' => 'attachment; filename="' . $fileName . '"',
));

如果你想从你的服务器以流的S3对象,那么你应该看看Streaming Amazon S3的对象从Web服务器文章对AWS PHP开发人员博客。

If you want to stream an S3 object from your server, then you should check out the Streaming Amazon S3 Objects From a Web Server article on the AWS PHP Developer Blog.