【发布时间】:2014-12-01 04:42:50
【问题描述】:
我正在使用托管在 Amazon Elastic Beanstalk 上的 php 创建我的第一个 Web 应用程序,但我有点不知所措。我的任务是访问最终客户在 AWS S3 云中指定的文件,将它们压缩,最后提供生成的 zip 文件的下载链接。我已经四处寻找一个我正在尝试做的事情的实例,但是我对 php 的缺乏经验一直是我确定某个解决方案是否适合我的障碍。
我发现了这个问题和回复here,并且看到它似乎在一般意义上解决了 php 和 zip 下载,我想我可能能够适应我的需要。以下是我在 php 中的内容:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require "./aws.phar";
use Aws\S3\S3Client;
$client = S3Client::factory(array(
'key' => getenv("AWS_ACCESS_KEY_ID"),
'secret' => getenv("AWS_SECRET_KEY")
));
echo "Starting zip test";
$client->registerStreamWrapper();
// make sure to send all headers first
// Content-Type is the most important one (probably)
//
header('Content-Type: application/octet-stream');
header('Content-disposition: attachment; filename="file.zip"');
// use popen to execute a unix command pipeline
// and grab the stdout as a php stream
// (you can use proc_open instead if you need to
// control the input of the pipeline too)
//
$fp = popen('zip -r - s3://myBucket/test.txt s3://myBucket/img.png', 'r');
// pick a bufsize that makes you happy (8192 has been suggested).
$bufsize = 8192;
$buff = '';
while( !feof($fp) ) {
$buff = fread($fp, $bufsize);
echo $buff;
}
pclose($fp);
这是我用来称呼它的:
$(document).ready(function() {
$("#download_button").click(function() {
$.get("../php/ZipAndDownload.php", function(data){alert(data)});
return false;
});
});
我也试过了:
$(document).ready(function() {
$("#download_button").click(function() {
$.ajax({
url:url,
type:"GET",
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
});
});
现在,每当我单击下载按钮时,我都会收到“开始 zip 测试”的回声,而没有其他任何内容。没有错误,也没有 zip 文件。我需要知道什么或我做错了什么?
提前感谢您的帮助和建议。
编辑: 以下是我在听取了 Derek 的建议后得到的。这仍然会产生一大串讨厌的二进制文件。
<?php
header('Content-Type: application/octet-stream');
header('Content-disposition: attachment; filename="file.zip"');
require "./aws.phar";
use Aws\S3\S3Client;
$bucket = 'myBucket';
$client = S3Client::factory(array(
'key' => getenv('AWS_ACCESS_KEY_ID'),
'secret' => getenv('AWS_SECRET_KEY')
));
$result = $client->getObject(array(
'Bucket' => $bucket,
'Key' => 'test.txt',
'SaveAs' => '/tmp/test.txt'
));
$Uri = $result['Body']->getUri();
$fp = popen('zip -r - '.$Uri, 'r');
$bufsize = 8192;
$buff = '';
while( !feof($fp) ) {
$buff = fread($fp, $bufsize);
echo $buff;
}
pclose($fp);
?>
【问题讨论】:
-
你正在使用popen,这意味着你正在执行一个外部程序。命令行应用程序绝对不知道
s3://etc...是什么意思。他们不处理 URL。他们处理文件系统路径。如果您在 unix/windows 上,您最多可以使用 NFS 或 UNC 路径。
标签: php amazon-web-services amazon-s3 zip