使用PHP的Heroku上的AmazonS3


Amazon S3 on Heroku with PHP

我想为我的Heroku应用程序启用我的AmazonS3存储桶。

在Heroku之前,我使用s3fs直接装载目录。既然这在Heroku上是不可能的,有没有其他方法可以将它们"链接"在一起,可能是通过保持上传(和调整大小)脚本仍然有效?

我想这仍然是可能的。您看过使用AWS S3存储静态资产和文件上传吗?

根据脚本的作用,您可能需要对它们进行一些更改。

首先,我应该声明我从未这样做过,所以我可能会错过一些细节,但根据我使用PHP、Heroku和S3的经验,这应该很简单,只需接受上传的文件(将存储在Heroku服务器上的临时目录中),调整其大小,最后将其上传到S3。

如果您已经有了上传工作流程,那么唯一的区别应该是,您现在将把文件上传到S3,而不是把文件保存到服务器中的一个目录(根据您的说法,这实际上是一个指向S3存储桶的符号链接)。使用此库可以轻松完成此操作:https://github.com/tpyo/amazon-s3-php-class

类似这样的东西:

// Ink is expensive, let's write less
$file = $_FILES['uploadedfile']['tmp_name'];
$name = $_FILES['pictures']['name'];
// Resize the image
resize($file);
// Normally you would do this for storing the file locally
// move_uploaded_file($file, "$destinationdir/$name");
// Now you want to upload to S3
$s3 = new S3($awsAccessKey, $awsSecretKey);
$s3->putObject($s3->inputFile($file, false), $bucketName, $uploadName, S3::ACL_PUBLIC_READ)

根据您组织上传的方式,您可能还想记录存储桶名称和文件名,可能是在数据库表中,您可以在其中搜索文件名并获得存储桶名称,因为检索文件需要两者。

您需要手动获取上传的文件并上传到S3,请记住,Heroku有一个只读文件系统,所以您不能在Heroku应用程序上创建临时文件,每个操作都需要在内存中完成。

这里是S3 php api

例如:

// get uploaded file
$file = $_FILES['uploadedfile']['tmp_name'];
// do whatever manipulation on the file in memory
// $file = resize($file)
// upload file to S3, note, S3->putObjectFile won't work, as it require $file parameter to be string
if (S3::putObject(S3::inputFile($file), $bucket, $uri, S3::ACL_PRIVATE)) {
    echo "File uploaded.";
} else {
    echo "Failed to upload file.";
}

更新

看起来S3 php lib没有从内存上传资源的api,S3::inputFile需要一个字符串作为输入,而不是内存资源。因此得出的结论是:在Heroku 上使用S3 PHP客户端是不可能的