OSS,全称 Object Storage Service,是阿里云提供的一种海量、安全、低成本、高可靠的云存储服务。可以用来存储和处理各种非结构化数据(如图片、音频、视频、日志等)。本文主要介绍如何利用OSS进行文件上传。
可以参考下官方示例代码,然后我们按照自己需要进行修改就基本上能实现了。这里是修改后的代码,因为只需将视频上传到OSS中,而且上传后的地址也是知道的,所以就注释了上传回调相关的操作,代码如下:
<?php
namespace app\oss\controller;
use app\common\controller\BaseController;
use app\common\controller\Common;
class Index extends BaseController
{
private $id = '';// 请填写您的AccessKeyId。
private $key = '';// 请填写您的AccessKeySecret。
private $host = "";// $host的格式为 bucketname.endpoint
private $callbackUrl = '';
function gmt_iso8601($time)
{
return str_replace('+00:00', '.000Z', gmdate('c', $time));
}
function callback()
{
$data = $this->getArgsList(['filename', 'mimeType', 'size', 'height', 'width']);
$data['url'] = $this->host . '/' . $data['filename'];
echo json_encode(Common::errorArray(0,"ok",$data));
}
/**
* 获取oss上传信息
*/
function getOss()
{
$dir = date('Ymd') . '/'; // 用户上传文件时指定的前缀。
$callback_param = array(
'callbackUrl' => $this->callbackUrl,
'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
'callbackBodyType' => "application/x-www-form-urlencoded"
);
$callback_string = json_encode($callback_param);
$base64_callback_body = base64_encode($callback_string);
$now = time();
$expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间,将不能访问。
$end = $now + $expire;
$expiration = $this->gmt_iso8601($end);
//最大文件大小.用户可以自己设置
$condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
$conditions[] = $condition;
// 表示用户上传的数据,必须是以$dir开始,不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录。
$start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
$conditions[] = $start;
$arr = array('expiration' => $expiration, 'conditions' => $conditions);
$policy = json_encode($arr);
$base64_policy = base64_encode($policy);
$string_to_sign = $base64_policy;
$signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->key, true));
$response = array();
$response['ossaccessKeyId'] = $this->id;
$response['host'] = $this->host;
$response['policy'] = $base64_policy;
$response['signature'] = $signature;
$response['expire'] = $end;
$response['callback'] = $base64_callback_body;
$response['dir'] = $dir; // 这个参数是设置用户上传文件时指定的前缀。
echo json_encode(Common::errorArray(0,"ok",$response));
}
}