'How to upload pic to Amazon s3 bucket and subfolder and display using php foreach
I am using the code here: http://net.tutsplus.com/tutorials/php/how-to-use-amazon-s3-php-to-dynamically-store-and-manage-files-with-ease/
...to create a bucket and subdirectories for users who upload pics for personal use when logged in.
After uploading the pics successfully to the s3 server, they are displayed in the html file in a list as such:
<ul id="sortable-list">
<?php
$i = 0;
$contents = $s3->getBucket("bucket_name");
foreach($contents as $file)
{
$fname = $file['name'];
$furl = "http://bucket_name.s3.amazonaws.com/".$fname;
echo "<li class=\"default\"><img src=\"$furl\" width=\"100\"></li>";
{
$i = 0;
}
}
?>
</ul>
For some reason, the subfolder is getting recognized as a file inside the bucket and fills the first element of the $contents as http://bucket_name.s3.amazonaws.com/subfolder/, but of course is empty without referencing a filename.
The php I'm using is a modified form of page.php on the tutsplus.com tutorial referenced above. The code that pertains to the creation of the bucket and sub-directories is here:
if(isset($_POST['Submit'])){
$fileName = $_FILES['theFile']['name'];
$fileTempName = $_FILES['theFile']['tmp_name'];
$folderName = "subfolder/$fileName";
$s3->putBucket("unique_id", S3::ACL_PUBLIC_READ);
if ($s3->putObjectFile($fileTempName, "unique_id", $folderName, S3::ACL_PUBLIC_READ)) {
echo "<strong>We successfully uploaded your file.</strong>";
}else{
echo "<strong>Something went wrong while uploading your file... sorry.</strong>";
}
}
Need help figuring out how to prevent the subfolder from being recognized as a file and creating an element in in the display. Thanks much
Solution 1:[1]
after using putbucket() function use $folder name like this:
$s3->putBucket("file_bucket", S3::ACL_PUBLIC_READ);
$foldername = "anirudh/$fileName";
and after that use these function
if ($s3->putObjectFile($fileTempName, "file_bucket",
$foldername, S3::ACL_PUBLIC_READ))
Solution 2:[2]
step 1 : download library from https://github.com/tpyo/amazon-s3-php-class/blob/master/S3.php
Step 2 : configure it in your project
Step 3 : follow below code
$fileTempName= $_FILES["file"]['tmp_name'];
$bucket_name = "your_bucket_name";
$upload_folder ="foldername" (which is created by you (folder) in aws )
$companyId = "subfolder name";
$s3 = new S3("your access_key", "your secret_key"));
$s3->putObject($fileTempName,$bucket_name,$upload_folder.'/'.$companyId);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ASGM |
| Solution 2 | Devang Hire |
