1.首先下载官方的PHP-SDK包
下载地址:
要求php运行版本至少5.5
(也可以在这里找)
2.封装好调用类函数
<?php
require __DIR__ . ‘/aws/aws-autoloader.php’; //看自己的目录引入自动加载类
/**
* AWS S3 cloud storage (云存储仓库)
* API wiki:
*/
class aws_s3
{
const SDK_VERSION = ‘latest’; //SDK version
private static $instance = array(); // 单例模式
/**
* 静态变量所有实例公用
* @var array
*/
private static $config = array(
‘version’ => self::SDK_VERSION,
);
/**
* set configured params(设置配置参数)
* @param array $config
* version – SDK version
* region – storage’s region 必填
* key – Access key ID 必填
* secret – Secret access key 必填
*/
public static function setConfig($config)
{
foreach ($config as $key => $val) {
self::$config[$key] = $val;
}
}
/**
* get signed token for uploading from client(获取用于客户端/前端直传文件的上传凭证)
* @param string $ Bucket 空间名
* @param array $ops 表单控制参数
* @param array $form_inputs 表单控制参数
* @param string $ expires demo:+1 hours|+20 minutes 有效时间
* @return array
*/
public static function getUploadToken($bucket, $ops, $form_inputs, $expires)
{
$client = self::getS3Client(self::$config);
$post_object = new \Aws\S3\PostObjectV4(
$client,
$bucket,
$form_inputs,
$ops,
$expires
);
return array(
‘attributes’ => $post_object->getFormAttributes(),
‘inputs’ => $post_object->getFormInputs()
);
}
/**
* create bucket(创建新空间)
* @param string $bucket 空间名
* @param array $ops 其他非必选控制参数
* @return array
*/
public static function createBucket($bucket, $ops = array())
{
$ops[‘Bucket’] = $bucket;
return self::getS3Client(self::$config)->createBucket($ops);
}
/**
* upload local file (直接通过API直传文件)
* @param string $bucket 空间名
* @param string $key 资源名称
* @param string $file_path 本地文件路径
* @param array $ops 其他非必选控制
* @return array
*/
public static function putObject($bucket, $key, $file_path, $ops = array())
{
$ops[‘Bucket’] = $bucket;
$ops[‘Key’] = $key;
$ops[‘Body’] = fopen($file_path, ‘r’);
!isset($ops[‘ACL’]) ? $ops[‘ACL’] = ‘private’ : null;
return self::getS3Client(self::$config)->putObject($ops);
}
/**
* get file description info (获取文件的描述信息,可以拿到文件的 hash (ETag)值等信息)
* @param string $bucket bucket
* @param string $key resource key
* @param array $ops optional parameters
* @return \Aws\Result
*/
public static function getObject($bucket, $key, $ops = array())
{
$ops[‘Bucket’] = $bucket;
$ops[‘Key’] = $key;
return self::getS3Client(self::$config)->getObject($ops);
}
/**
* get instance of S3Client(单例模式)
* @param array $config
* @return \Aws\S3\S3Client
*/
public static function getS3Client($config = array())
{
empty($config) ? $config = self::$config : null;
$hash = md5(serialize($config));
if(!isset(self::$instance[‘s3_client’.$hash])){
self::$instance[‘s3_client’.$hash] = new \Aws\S3\S3Client(array(
‘version’ => $config[‘version’],
‘region’ => $config[‘region’],
‘credentials’ => array(
‘key’ => $config[‘key’],
‘secret’ => $config[‘secret’]
)
));
}
return self::$instance[‘s3_client’.$hash] ;
}
}
3.构造上传凭证
<?php
$s3_lib = new aws_s3();
$config = array(
‘key’ => ‘Access key ID’,
‘secret’ => ‘Secret access key’,
‘region’ => ‘ap-northeast-1’, //根据自己创建空间时设置的region节点填写
);
$s3_lib->setConfig($config);
$bucket = ‘your bucket’;//存储仓库名称
$file_type = ‘jpg’;
$key = uniqid() . mt_rand(100000, 999999) . ‘.’ . $file_type; //文件的resource key
$content_type = ‘image/’ . $ file _type; //上传文件类型
$acl = ‘public-read’; //访问策略
$status = ‘201’;//成功返回HTTP_CODE状态值,只有201时响应才有XML内容,不然200是没有内容的
$expires = ‘+1 hours’; //凭证有效时间
//将上面的参数构造成控制策略
$options = [
[‘acl’ => $acl], //private|public-read|public-read-write|authenticated-read
[‘bucket’ => $bucket], //空间
[‘starts-with’, ‘$key’, $key], //文件resource key
[‘starts-with’, ‘$Content-Type’, $content_type], //上传文件格式
[‘success_action_status’ => $status], //成功返回HTTP_CODE状态值
//[‘success_action_redirect’ => $redirect_url], //跳转链接(如果是网页端的话才需要,APP端不需要)
[‘content-length-range’, 0, 10 * 1024 * 1024] //文件大小限制,限制10M
] ;
$form_inputs = [
‘acl’ => $acl
];
$result = $s3_lib->getUploadToken($bucket, $options, $form_inputs, $expires);
//将构造表单需要的参数全部完整封装
$data = array();
foreach ($result[‘inputs’] as $k => $v) {
$data[$k] = $v;
}
$data[‘key’] = $key;
$data[‘Content-Type’] = $content_type;
$data[‘success_action_status’] = $status;
$response = array(
‘url’ => $result[‘attributes’][‘action’],
‘inputs’ => $data //input的参数和参数值,最后一个参数必须为file文件
);
//将这个参数直接返回给客户端去构造上传表单就可以了。
echo json_encode($response);
4.构造上传表单
<form action=”<?php echo $responese[‘url’]; ?>” method=”POST” enctype=”multipart/form-data”>
<?php foreach($response as $key => $val){
<input type=”hidden” name=”<?php echo key; ?>” value=”<?php echo $val; ?>”>
<?php } ?>
<input type=”file” name=”file” value=”” >
<input type=”submit” value=”Submit”>
</form>
之前网上找了好多案例,但是感觉都写得不是很少,主要是构造上传凭证以及输出给客户端的上传参数这块很容易出错和遗漏,官方给的deom对这块的使用场景也介绍得不是很少。可能我英文比较差吧,看了好久再结合网上的各种案例才搞定的。
然后顺便提一下,如果遇到签名不匹配或者权限的问题的话,最好核实一下后台的配置,一般如果在AWS CLI(Linux的命令行工具)都不能通过命令上传的话,那基本就是后台的配置问题了。
安装aws cli教程:
使用教程: