2017-07-15 74 views
0

我有一個學校項目,我認爲一切進展順利,然後我部署它,發現用戶無法上傳圖像到heroku上,因爲它的臨時文件系統。我的整個應用程序都以用戶上傳圖像爲中心。上傳文件到S3在PHP中

我在某處讀取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)我不確定這是什麼意思,我怎麼知道用戶上傳的文件名是什麼?

+0

你不會把這個放在'index.php'中的一個現有的應用程序中。這是一個獨立的示例/演示應用程序。 –

回答

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上已存在相同名稱的文件,則它將被替換。也許他們描述了這個問題。可以使用動態文件名。