【问题标题】:Uploading Files to S3 in PHP在 PHP 中将文件上传到 S3
【发布时间】:2017-12-20 18:01:16
【问题描述】:

我有一个学校项目,我认为一切进展顺利,然后我部署了它,发现由于 Heroku 的临时文件系统,用户无法将图像上传到 Heroku。我的整个应用程序几乎都围绕着用户上传图像。

我在某处阅读以通过 AWS S3 存储工作。所以我按照https://devcenter.heroku.com/articles/s3 的说明进行操作。

我已经完成了大部分配置过程,但最后它说:

将以下内容放入名为index.php的文件中

<?php
require('vendor/autoload.php');
// this will simply read AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY from env vars
$s3 = Aws\S3\S3Client::factory();
$bucket = getenv('S3_BUCKET')?: die('No "S3_BUCKET" config var in found in env!');
?>
<html>
    <head><meta charset="UTF-8"></head>
    <body>
        <h1>S3 upload example</h1>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['userfile']) && $_FILES['userfile']['error'] == UPLOAD_ERR_OK && is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    // FIXME: add more validation, e.g. using ext/fileinfo
    try {
        // FIXME: do not use 'name' for upload (that's the original filename from the user's computer)
        $upload = $s3->upload($bucket, $_FILES['userfile']['name'], fopen($_FILES['userfile']['tmp_name'], 'rb'), 'public-read');
?>
        <p>Upload <a href="<?=htmlspecialchars($upload->get('ObjectURL'))?>">successful</a> :)</p>
<?php } catch(Exception $e) { ?>
        <p>Upload error :(</p>
<?php } } ?>
        <h2>Upload a file</h2>
        <form enctype="multipart/form-data" action="<?=$_SERVER['PHP_SELF']?>" method="POST">
            <input name="userfile" type="file"><input type="submit" value="Upload">
        </form>
    </body>
</html>

两个问题:

它没有说明将index.php 放在哪里。我假设它位于项目根目录中。

我的另一个问题是代码本身。在第 15 行他们说 do not use 'name' for upload (that's the original filename from the user's computer) 我不确定这是什么意思,我怎么知道用户上传的文件名是什么?

【问题讨论】:

  • 您不会将其放在现有应用程序中的index.php 中。这是一个独立的示例/演示应用程序。

标签: php amazon-web-services heroku amazon-s3


【解决方案1】:

1) 您可以将 index.php 放在项目根文件夹或其他包含核心文件的文件夹中(在您的情况下为自动加载)。 2) 名称 - 它是文件名。例如:

<form method="post" action="index.php">
<input type="file" name="myfile">
<button>Submit</button>
</form>

在这种情况下,您应该使用['myfile']['name']。 如果您需要修改文件名(或使用唯一名称),可以添加 time().'_'.$_FILES['userfile']['name'] 之类的内容。

如果文件名等于$_FILES['userfile']['name'],则文件将以您上传的相同名称保存。例如,如果您上传 file.txt,但 S3 上已存在同名文件,则该文件将被替换。也许他们描述了这个问题。可以使用动态文件名。

【讨论】:

    猜你喜欢
    • 2011-07-21
    • 2019-03-04
    • 1970-01-01
    • 2021-08-30
    • 2018-07-03
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多