如何加载到aws

时间:2015-12-21 21:29:12

标签: php laravel amazon-web-services

我有一个用于文件存储的aws帐户设置。我正在尝试设置视图,以便文件加载到特定文件夹,我找不到解决此问题的答案。我搜索过这个网站,但无法找到像我这样的代码,我对php有点新鲜。我的代码直接来自heroku和aws指南。

我的理解是我必须设置$ keyPrefix,但我似乎无法做到正确。任何帮助将不胜感激。

<?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!');
  $keyPrefix = 'assets/avatars/';
?>

<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'])) {
print_r($_FILES, $keyPrefix);

    // 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="/aws/upload" method="POST">
        <input name="userfile" type="file">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        <input type="submit" value="Upload">
     </form>
  </body>

1 个答案:

答案 0 :(得分:1)

我不确定您使用的是哪个版本的AWS库,但最新的似乎没有upload方法。相反,我建议使用putObject方法,就像他们的Github页面上的示例节目一样。 (或者,检查您正在使用的s3客户端的版本,我们可以看看它是否有所不同。)

来自Github readme which has an example

<?php
// Upload a publicly accessible file. The file size and type are determined by the SDK.
try {
    $s3->putObject([
        'Bucket' => 'my-bucket',
        'Key'    => 'my-object',
        'Body'   => fopen('/path/to/file', 'r'),
        'ACL'    => 'public-read',
    ]);
} catch (Aws\Exception\S3Exception $e) {
    echo "There was an error uploading the file.\n";
}

更多complete docs are here