php 直传图片到腾讯云oss

sts.php代码如下

<?php
// 临时密钥计算样例

include './qcloud-sts-sdk.php'; // 这里获取 sts.php https://github.com/tencentyun/qcloud-cos-sts-sdk/blob/master/php/sts/sts.php
$sts = new STS();
// 配置参数
$config = array(
    'url' => 'https://sts.tencentcloudapi.com/',
    'domain' => 'sts.tencentcloudapi.com',
    'proxy' => '',
    'secretId' => '', // 固定密钥
    'secretKey' => '', // 固定密钥
    'bucket' => 'zhichuan-1304188111', // 换成你的 bucket
    'region' => 'ap-beijing', // 换成 bucket 所在园区
    'durationSeconds' => 1800, // 密钥有效期
    // 允许操作(上传)的对象前缀,可以根据自己网站的用户登录态判断允许上传的目录,例子: user1/* 或者 * 或者a.jpg
    // 请注意当使用 * 时,可能存在安全风险,详情请参阅:https://cloud.tencent.com/document/product/436/40265
    'allowPrefix' => '*',
    // 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
    'allowActions' => array (
        // 所有 action 请看文档 https://cloud.tencent.com/document/product/436/31923
        // 简单上传
        'name/cos:PutObject',
        'name/cos:PostObject',
        // 分片上传
        'name/cos:InitiateMultipartUpload',
        'name/cos:ListMultipartUploads',
        'name/cos:ListParts',
        'name/cos:UploadPart',
        'name/cos:CompleteMultipartUpload'
    )
);
// 获取临时密钥,计算签名
$tempKeys = $sts->getTempKeys($config);

// 返回数据给前端
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: http://127.0.0.1'); // 这里修改允许跨域访问的网站
header('Access-Control-Allow-Headers: origin,accept,content-type');
echo json_encode($tempKeys);

qcloud-sts-sdk.php

<?php

class STS{
    // 临时密钥计算样例

    function _hex2bin($data) {
        $len = strlen($data);
        return pack("H" . $len, $data);
    }
    // obj 转 query string
    function json2str($obj, $notEncode = false) {
        ksort($obj);
        $arr = array();
        if(!is_array($obj)){
            throw new Exception($obj + " must be a array");
        }
        foreach ($obj as $key => $val) {
            array_push($arr, $key . '=' . ($notEncode ? $val : rawurlencode($val)));
        }
        return join('&', $arr);
    }
    // 计算临时密钥用的签名
    function getSignature($opt, $key, $method, $config) {
        $formatString = $method . $config['domain'] . '/?' . $this->json2str($opt, 1);
        $sign = hash_hmac('sha1', $formatString, $key);
        $sign = base64_encode($this->_hex2bin($sign));
        return $sign;
    }
    // v2接口的key首字母小写,v3改成大写,此处做了向下兼容
    function backwardCompat($result) {
        if(!is_array($result)){
            throw new Exception($result + " must be a array");
        }
        $compat = array();
        foreach ($result as $key => $value) {
            if(is_array($value)) {
                $compat[lcfirst($key)] = $this->backwardCompat($value);
            } elseif ($key == 'Token') {
                $compat['sessionToken'] = $value;
            } else {
                $compat[lcfirst($key)] = $value;
            }
        }
        return $compat;
    }
    // 获取临时密钥
    function getTempKeys($config) {
        if(array_key_exists('bucket', $config)){
            $ShortBucketName = substr($config['bucket'],0, strripos($config['bucket'], '-'));
            $AppId = substr($config['bucket'], 1 + strripos($config['bucket'], '-'));
        }
        if(array_key_exists('policy', $config)){
            $policy = $config['policy'];
        }else{
            $policy = array(
                'version'=> '2.0',
                'statement'=> array(
                    array(
                        'action'=> $config['allowActions'],
                        'effect'=> 'allow',
                        'principal'=> array('qcs'=> array('*')),
                        'resource'=> array(
                            'qcs::cos:' . $config['region'] . ':uid/' . $AppId . ':prefix//' . $AppId . '/' . $ShortBucketName . '/' . $config['allowPrefix']
                        )
                    )
                )
            );
        }
        $policyStr = str_replace('\\/', '/', json_encode($policy));
        $Action = 'GetFederationToken';
        $Nonce = rand(10000, 20000);
        $Timestamp = time();
        $Method = 'POST';
        $params = array(
            'SecretId'=> $config['secretId'],
            'Timestamp'=> $Timestamp,
            'Nonce'=> $Nonce,
            'Action'=> $Action,
            'DurationSeconds'=> $config['durationSeconds'],
            'Version'=>'2018-08-13',
            'Name'=> 'cos',
            'Region'=> 'ap-guangzhou',
            'Policy'=> urlencode($policyStr)
        );
        $params['Signature'] = $this->getSignature($params, $config['secretKey'], $Method, $config);
        $url = $config['url'];
        $ch = curl_init($url);
        if(array_key_exists('proxy', $config)){
            $config['proxy'] && curl_setopt($ch, CURLOPT_PROXY, $config['proxy']);
        }
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->json2str($params));
        $result = curl_exec($ch);
        if(curl_errno($ch)) $result = curl_error($ch);
        curl_close($ch);
        $result = json_decode($result, 1);
        if (isset($result['Response'])) {
            $result = $result['Response'];
            $result['startTime'] = $result['ExpiredTime'] - $config['durationSeconds'];
        }
        $result = $this->backwardCompat($result);
        return $result;
    }

    // get policy
    function getPolicy($scopes){
        if (!is_array($scopes)){
            return null;
        }
        $statements = array();

        for($i=0, $counts=count($scopes); $i < $counts; $i++){
            $actions=array();
            $resources = array();
            array_push($actions, $scopes[$i]->get_action());
            array_push($resources, $scopes[$i]->get_resource());
            $principal = array(
                'qcs' => array('*')
            );
            $statement = array(
                'actions' => $actions,
                'effect' => 'allow',
                'principal' => $principal,
                'resource' => $resources
            );
            array_push($statements, $statement);
        }

        $policy = array(
            'version' => '2.0',
            'statement' => $statements
        );
        return $policy;
    }
}

class Scope{
    var $action;
    var $bucket;
    var $region;
    var $resourcePrefix;
    function __construct($action, $bucket, $region, $resourcePrefix){
        $this->action = $action;
        $this->bucket = $bucket;
        $this->region = $region;
        $this->resourcePrefix = $resourcePrefix;
    }
    function get_action(){
        return $this->action;
    }

    function get_resource(){
        $index = strripos($this->bucket, '-');
        $bucketName = substr($this->bucket, 0, $index);
        $appid = substr($this->bucket, $index + 1);
        if(!(strpos($this->resourcePrefix, '/') === 0)){
            $this->resourcePrefix = '/' . $this->resourcePrefix;
        }
        return 'qcs::cos:' . $this->region . ':uid/' . $appid . ':prefix//' . $appid . '/' . $bucketName . $this->resourcePrefix;
    }
}
?>

html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Ajax Put 上传</title>
  <style>
      h1, h2 {
          font-weight: normal;
      }
       #msg {
          margin-top: 10px;
      }
  </style>
</head>
<body>
<h1>Ajax Put 上传</h1>
<input id="fileSelector" type="file">
<input id="submitBtn" type="submit">
<div id="msg"></div>
<script src="https://unpkg.com/cos-js-sdk-v5/demo/common/cos-auth.min.js"></script>
<script>
  (function () {
      // 请求用到的参数
      var Bucket = 'zhichuan-1304188111';
      var Region = 'ap-beijing';
      var protocol = location.protocol === 'https:' ? 'https:' : 'http:';
      var prefix = protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com/';  // prefix 用于拼接请求 url 的前缀,域名使用存储桶的默认域名
       // 对更多字符编码的 url encode 格式
      var camSafeUrlEncode = function (str) {
          return encodeURIComponent(str)
              .replace(/!/g, '%21')
              .replace(/'/g, '%27')
              .replace(/\(/g, '%28')
              .replace(/\)/g, '%29')
              .replace(/\*/g, '%2A');
      };
       // 计算签名
      var getAuthorization = function (options, callback) {
          // var url = 'http://127.0.0.1:3000/sts-auth' +
          var url = 'sts.php';
          var xhr = new XMLHttpRequest();
          xhr.open('GET', url, true);
          xhr.onload = function (e) {
              var credentials;
              try {
                  credentials = (new Function('return ' + xhr.responseText))().credentials;
              } catch (e) {}
              if (credentials) {
                  callback(null, {
                      SecurityToken: credentials.sessionToken,
                      Authorization: CosAuth({
                          SecretId: credentials.tmpSecretId,
                          SecretKey: credentials.tmpSecretKey,
                          Method: options.Method,
                          Pathname: options.Pathname,
                      })
                  });
              } else {
                  console.error(xhr.responseText);
                  callback('获取签名出错');
              }
          };
          xhr.onerror = function (e) {
              callback('获取签名出错');
          };
          xhr.send();
      };
       // 上传文件
      var uploadFile = function (file, callback) {
          var Key = 'dir/' + file.name; // 这里指定上传目录和文件名
          getAuthorization({Method: 'PUT', Pathname: '/' + Key}, function (err, info) {
               if (err) {
                  alert(err);
                  return;
              }
               var auth = info.Authorization;
              var SecurityToken = info.SecurityToken;
              var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
              var xhr = new XMLHttpRequest();
              xhr.open('PUT', url, true);
              xhr.setRequestHeader('Authorization', auth);
              SecurityToken && xhr.setRequestHeader('x-cos-security-token', SecurityToken);
              xhr.upload.onprogress = function (e) {
                  console.log('上传进度 ' + (Math.round(e.loaded / e.total * 10000) / 100) + '%');
              };
              xhr.onload = function () {
                  if (/^2\d\d$/.test('' + xhr.status)) {
                      var ETag = xhr.getResponseHeader('etag');
                      callback(null, {url: url, ETag: ETag});
                  } else {
                      callback('文件 ' + Key + ' 上传失败,状态码:' + xhr.status);
                  }
              };
              xhr.onerror = function () {
                  callback('文件 ' + Key + ' 上传失败,请检查是否没配置 CORS 跨域规则');
              };
              xhr.send(file);
          });
      };
       // 监听表单提交
      document.getElementById('submitBtn').onclick = function (e) {
          var file = document.getElementById('fileSelector').files[0];
          if (!file) {
              document.getElementById('msg').innerText = '未选择上传文件';
              return;
          }
          file && uploadFile(file, function (err, data) {
              console.log(err || data);
              document.getElementById('msg').innerText = err ? err : ('上传成功,ETag=' + data.ETag);
          });
      };
  })();
</script>
</body>
</html>
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将图片上传腾讯云OSS,你需要进行以下步骤: 1. 在腾讯云中创建一个对象存储桶(Bucket)。 2. 在uniapp中安装并引入腾讯云OSS SDK。 3. 编写上传代码,包括以下步骤: - 获取上传凭证:在腾讯云中创建一个临时的密钥,用于上传图片。 - 创建上传任务:使用SDK提供的uploadObject方法,将图片进行上传。 - 监听上传进度:可以使用SDK提供的progress方法,获取上传进度信息。 这是一个示例代码,可以帮助你更好地理解上传图片腾讯云OSS的过程: ```javascript import COS from "cos-wx-sdk-v5"; const cos = new COS({ getAuthorization: async function (options, callback) { try { // 获取上传凭证 const res = await uni.request({ url: "上传凭证接口", method: "GET", }); const { credentials } = res.data; callback({ TmpSecretId: credentials.tmpSecretId, TmpSecretKey: credentials.tmpSecretKey, SecurityToken: credentials.sessionToken, StartTime: credentials.startTime, ExpiredTime: credentials.expiredTime, }); } catch (err) { console.log(err); } }, }); export default { methods: { async uploadFile(file, fileName) { try { // 创建上传任务 const res = await new Promise((resolve, reject) => { cos.uploadObject( { Bucket: "你的Bucket名称", Region: "你的Bucket所在地域", Key: fileName, FilePath: file.path, }, function (err, data) { if (err) { reject(err); } else { resolve(data); } } ).on("progress", function (info) { console.log(info.percent * 100 + "%"); }); }); console.log(res); } catch (err) { console.log(err); } }, }, }; ``` 这段代码中,首先引入了腾讯云OSS SDK,并创建了一个COS实例。在上传文件的方法中,首先调用了 `getAuthorization` 方法获取上传凭证,然后使用 `cos.uploadObject` 方法创建上传任务。同时,也可以使用 `on` 方法监听上传进度,以便实时更新上传进度。最后,上传完成后,会返回上传成功的信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值