2018-03-06 使用AWS PHP SDK將文件上傳到AMAZON S3

1、下載aws-sdk-php-laravel

git clone https://github.com/aws/aws-sdk-php-laravel.git

2、安裝aws-sdk-php

cd aws-sdk-php-laravel/
curl -sS https://getcomposer.org/installer | php #安裝 composer.phar
vim composer.json
修改如下內(nèi)容
image.png
php composer.phar update
php composer.phar require aws/aws-sdk-php #安裝aws-sdk-php

3、在AWS上創(chuàng)建一個(gè)存儲(chǔ)桶

[root@hostname-172-31-9-249 /data/wwwroot/aws-sdk-php-laravel]# vim create-bucket.php 

<?
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$bucketName = 'maiyuan2'; #存儲(chǔ)桶的名字
$client = new S3Client([
    'version' => 'latest',
    'region' => 'us-west-1', #要改為美國(guó)西部,不然會(huì)報(bào)錯(cuò)
    'credentials' => [
        'key'    => '', #訪問(wèn)秘鑰
        'secret' => '' #私有訪問(wèn)秘鑰
    ]
]);
try {
    $result = $client->createBucket([
        'Bucket' => $bucketName, // REQUIRED
        'ACL'    => 'public-read',
    ]);
} catch (Aws\S3\Exception\S3Exception $e) {
    // output error message if fails
    echo $e->getMessage();
}
?>
chmod +x create-bucket.php
cd vendor/
chmod +x autoload.php 
php create-bucket.php #執(zhí)行發(fā)現(xiàn)在aws上創(chuàng)建存儲(chǔ)桶成功

4、上傳文件到桶

[root@hostname-172-31-9-249 /data/wwwroot/aws-sdk-php-laravel]# vim upload-to-aws.php 

<?
require 'vendor/autoload.php';
use Aws\S3\S3Client;
// Instantiate an Amazon S3 client.
$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'us-west-1', #改為美國(guó)西部
    'credentials' => [
        'key'    => '', #訪問(wèn)秘鑰
        'secret' => '' #私有訪問(wèn)秘鑰
    ]
]);
$bucketName = 'maiyuan2'; #存儲(chǔ)桶的名字
$file_Path = '/data/wwwroot/aws-sdk-php-laravel/QQ圖片20180223091800.png'; #要上傳的文件的路徑
$key = basename($file_Path);
// Upload a publicly accessible file. The file size and type are determined by the SDK.
try {
    $result = $s3->putObject([
        'Bucket' => $bucketName,
        'Key'    => $key,
        'Body'   => fopen($file_Path, 'r'),
        'ACL'    => 'public-read',
    ]);
    echo $result->get('ObjectURL');
} catch (Aws\S3\Exception\S3Exception $e) {
    echo "There was an error uploading the file.\n";
    echo $e->getMessage();
}
?>
chmod +x upload-to-aws.php
php upload-to-aws.php #在S3上發(fā)現(xiàn)上傳圖片成功

本文參考:https://github.com/aws/aws-sdk-php-laravel
https://artisansweb.net/upload-files-amazon-s3-using-aws-php-sdk/
https://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容