在PHP中将文件上传到S3

时间:2017-07-15 22:21:33

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

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

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

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

将以下内容放入名为class AQueueable: PriorityQueuable, Comparable { var hashValue: Int { return 1 } var key: String = "Hi" var value: String = "YoMaMa" static func < (lhs: AQueueable, rhs: AQueueable) -> Bool { // implement code return false } static func == (lhs: AQueueable, rhs: AQueueable) -> Bool { // implement code return false } } class AQueue: PriorityQueue { var heap: AnyHeap = AnyHeap<AQueueable>(data: [AQueueable](), heapify: { parentIndex in // implement code }) }

的文件中
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> 的位置。我假设它进入项目根目录。

我的另一个问题是代码本身。在第15行,他们说index.php我不确定这意味着什么,我怎么知道用户上传的文件名是什么?

1 个答案:

答案 0 :(得分:1)

1)您可以将index.php放在项目根文件夹或带有核心文件的其他文件夹中(在您的情况下为autoload)。 2)name - 它的文件名。如前:

<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上已经存在同名文件,则会被替换。也许他们描述了这个问题。可以使用动态文件名。