版权声明:本文由贺嘉 原创文章,转载请注明出处: 
文章原文链接:https://www.qcloud.com/community/article/640268001487425627

来源:腾云阁 https://www.qcloud.com/community

一、实验简介

本实验通过调用腾讯云对象存储(COS)接口,实现将图片上传到指定的 Bucket 功能;同时封装图片上传接口,用于上传商品图片。

二、实验目标

  1. 掌握 RESTFul API 接口调用和调试方法
  2. 掌握 RESTFul API 封装方法

三、实验步骤

3.1 添加云应用

第一步: clone xqcloud 项目

1. cd <your project path>
2. git clone https://git.oschina.net/xpmjs/xqcloud.git xqcloud

第二步: 修改远程仓库地址,提交到远程仓库

1. git remote remove origin
2. git remote add origin ssh://git@dev.appcook.cn:2222/source/xqcloud.git
3. git push origin master

3.2 调用 COS API,实现文件上传功能

第一步: 编写 Cos Model vi xqcloud/model/Cos.php

1. <?php
2. use \Tuanduimao\Mem as Mem;
3. use \Tuanduimao\Excp as Excp;
4. use \Tuanduimao\Err as Err;
5. use \Tuanduimao\Conf as Conf;
6. use \Tuanduimao\Model as Model;
7. use \Tuanduimao\Utils as Utils;
8. use \Tuanduimao\Loader\App as App;
9. /**
10. * cos对象存储11. */
12. class CosModel {
13. function __construct( $opt=[] ) {
14. $this->appid = isset($opt['appid']) ? $opt['appid'] : "";
15. $this->bucket = isset($opt['bucket']) ? $opt['bucket'] : "";
16. $this->SecretID = isset($opt['SecretID']) ? $opt['SecretID'] : "";
17. $this->SecretKey = isset($opt['SecretKey']) ? $opt['SecretKey'] : "";
18. }
19. /**
20. * 签名
21. * @param array $opt [description]
22. * @return [type] [description]
23. */
24. function sign( $opt=[] ) {
25. $randstr= $this->generateId(10);
26. $t = isset($opt['e']) ? time()+86400 : 0;
27. $a = isset($opt['appid']) ? $opt['appid'] : $this->appid;
28. $b = isset($opt['bucket']) ? $opt['bucket'] : $this->bucket;
29. $k = isset($opt['SecretID']) ? $opt['SecretID'] : $this->SecretID;
30. $e = isset($opt['e']) ? $opt['e'] : time()+3600;
31. $SecretKey = isset($opt['SecretKey']) ? $opt['SecretKey'] : $this->SecretKey;
32. $s = [
33. "a" => $a,
34. "b" => $b,
35. "k" => $k,
36. "e" => $e,
37. "t" => time(),
38. "r" => $randstr,
39. "f" =>$opt['file'],
40. ];
41. // 拼接字符串
42. $orignal = "a={$s['a']}&k={$s['k']}&e={$s['e']}&t={$s['t']}&r={$s['r']}&f={$s['f']}&b={$s['b']}";
43. $signTmp = hash_hmac( 'SHA1', $orignal, $SecretKey , true );
44. $sign = base64_encode($signTmp.$orignal);
45. return $sign;
46. }
47.
48. /**
49. * 文件转.字符串
50. * @param [type] $imageUrl [description]
51. * @param array $opt [description]
52. * @return [type] [description]
53. */
54. function uploadByUrl( $imageUrl, $opt=[] ) {
55. $imageData = file_get_contents( $imageUrl );
56. return $this->upload( $imageData, $opt );
57. }
58.
59. /**
60. * 文件上传61. * @param [type] $imageData [description]
62. * @param array $opt [description]
63. * @return [type] [description]S
64. */
65. function upload( $imageData, $opt=[] ){
66. // 生成随机数

第二步: 编写测试用控制器 vi xqcloud/controller/Cos.php

1. <?php
2. use \Tuanduimao\Loader\App as App;
3. use \Tuanduimao\Utils as Utils;
4. use \Tuanduimao\Tuan as Tuan;
5. use \Tuanduimao\Excp as Excp;
6. use \Tuanduimao\Conf as Conf;
7.
8. class CosController extends \Tuanduimao\Loader\Controller {
9.
10. function __construct() {
11. }
12.
13. function tryit() {
14.
15. $config = [
16. 'region'=>'<tj/sh/gd>',
17. 'appid'=>'<your appid>',
18. 'bucket'=>'<your bucket>',
19. 'SecretID'=>"<your SecretID>",
20. 'SecretKey'=>"<your SecretKey>"
21. ];
22. $cos = App::M('Cos',$config);
23. $content =file_get_contents("http://7xleg1.com1.z0.glb.clouddn.com/x1/2/lab/uploadit.jpg");
24. $resp = $cos->upload( $content, ['region'=>$config['region'], '
filetype'=>'jpg'] );
25. Utils::out($resp);
26. }
27.
28. }

第三步: 提交代码并更新线上

1. git add *
2. git commit -m '+COS Tryit {{pull}}' # {{pull}} feed 指令更新线上代码
3. git push

第四步: 安装 XQCloud 应用
访问 https://dev.appcook.cn/core-system/appmanager/index , 安装应用

第五步: 登录云主机,运行测试

1. docker exec -it xpmjs-server /bin/bash # 进入容器
2. tdm app run /apps/xqcloud/controller/Cos.php tryit # 运行测试

3.3 封装图片上传接口

第一步: 创建配置文件 vi xqcloud/config.php

1. <?php
2. $GLOBALS['_QC'] = [
3. 'cos'=>[
4. 'region'=>'<tj/sh/gd>',
5. 'appid'=>'<your appid>',
6. 'bucket'=>'<your bucket>',
7. 'SecretID'=>"<your SecretID>",
8. 'SecretKey'=>"<your SecretKey>"
9. ]
10. ];

第二步: 修改控制器 vi xqcloud/controller/Cos.php

1. <?php
2. require_once(__DIR__ . '/../config.php');
3. use \Tuanduimao\Loader\App as App;
4. use \Tuanduimao\Utils as Utils;
5. use \Tuanduimao\Tuan as Tuan;
6. use \Tuanduimao\Excp as Excp;
7. use \Tuanduimao\Conf as Conf;
8.
9. class CosController extends \Tuanduimao\Loader\Controller {
10.
11. function __construct() {
12. }
13.
14. /**
15. * 上传文件接口
16. * @return [type] [description]
17. */
18. function upload() {
19.
20. $file = !empty($_FILES['wxfile']) ? $_FILES['wxfile'] : [];
21. $content = !empty($file['content']) ?base64_decode($file['content']) : NULL;
22. $filetype = Utils::mimes()->getExtension($file['type']);
23.
24. if ( $content == null ) {
25. echo (new Excp("未接收到文件", 502, ['_FILES'=>$_FILES]))->toJSON();
26. return;
27. }
28.
29. $config = $GLOBALS['_QC']['cos'];
30. $cos = App::M('Cos',$config);
31. try {
32. $resp = $cos->upload( $content, ['region'=>$config['region' ], 'filetype'=>$filetype] );
33. } catch( Excp $e ){
34. $extra = $e->getExtra();
35. echo (new Excp("COS API 错误", 502, ['resp'=>$resp, 'e'=>$extra]))->toJSON();
36. return;
37. }
38. if ( $resp['code'] == 0) {
39. Utils::out($resp['data']);
40. return;
41. }
42. echo (new Excp("COS API 错误", 502, ['resp'=>$resp]))->toJSON();
43. return;
44.
45. }
46. }

第三步: 提交代码更新

1. git add *
2. git commit -m '+COS Upload {{pull}}' # {{pull}} feed 指令更新线上代码
3. git push

第四步: 登录云主机,运行测试

1. docker exec -it xpmjs-server /bin/bash # 进入容器
2. cd ~
3. wget http://wxapp-1252011659.file.myqcloud.com/4883017283.jpg
4. tdm app run /apps/xqcloud/controller/Cos.php upload --f='''{"wxfile":"4883017283.jpg"}''' --vv

四、实验结果

通过调用 COS 接口,掌握 RESTFul API 调用和调试的方法;通过封装图片上传接口,掌握
RESTFul API 的封装方法。

如果你看了以上的文章觉得不过瘾。想要系统性学习如何在腾讯云上开发微信小程序,建议报名参加我们的TCCE微信开发课程培训:https://www.qcloud.com/training/courses/wx-dev

如何用Baas快速在腾讯云上开发小程序-系列3 :实现腾讯云COS API调用的更多相关文章

  1. 如何用Baas快速在腾讯云上开发小程序-系列4:实现客户侧商品列表、商品详情页程序

    版权声明:本文由贺嘉 原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/431172001487671163 来源:腾云阁 h ...

  2. 如何用Baas快速在腾讯云上开发小程序-系列1:搭建API & WEB WebSocket 服务器

    版权声明:本文由贺嘉 原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/221059001487422606 来源:腾云阁 h ...

  3. 如何用Baas快速在腾讯云上开发小程序-系列2:搭建Phabricator开发管理平台

    版权声明:本文由贺嘉 原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/905333001487424158 来源:腾云阁 h ...

  4. 《腾讯游戏人生》微信小程序开发总结

    为打通游戏人生擂台赛与线下商家的O2O衔接,同时响应时下日臻火热的微信小程序,项目团队决定也开发一款针对性的微信小程序,以此方便商家在我们平台入驻并进行擂台赛事的创建和奖励的核销,进一步推广擂台赛的玩 ...

  5. 微信小程序又一爆炸功能上线-云开发

    云开发介绍 开发者可以使用云开发开发微信小程序.小游戏,无需搭建服务器,即可使用云端能力. 云开发为开发者提供完整的云端支持,弱化后端和运维概念,无需搭建服务器,使用平台提供的 API 进行核心业务开 ...

  6. 最强CP!阿里云联手支付宝小程序如何助力双11?

    作为首次“全面上云”的双11,阿里云征服了每秒订单峰值54.4万笔的世界新记录.正是在阿里云的保驾护航下,即使访问量是平时的5到6倍,小程序也鲜少出现卡顿或者宕机的现象,“依靠阿里云,我们整个天猫双1 ...

  7. 微信小程序存放视频文件到阿里云用到算法js脚本文件

           peterhuang007/weixinFileToaliyun: 微信小程序存放视频文件到阿里云用到算法js脚本文件 https://github.com/peterhuang007/ ...

  8. 微信小程序/网站 上传图片到腾讯云COS

    COS简介: 腾讯云提供的一种对象存储服务,供开发者存储海量文件的分布式存储服务.可以将自己开发的应用的存储部分全部接入COS的存储桶中,有效减少应用服务器的带宽,请求等.个人也可以通过腾讯云账号免费 ...

  9. 腾讯云&搭建微信小程序服务

    准备域名和证书 任务时间:20min ~ 40min 小程序后台服务需要通过 HTTPS 访问,在实验开始之前,我们要准备域名和 SSL 证书. 域名注册 如果您还没有域名,可以在腾讯云上选购,过程可 ...

随机推荐

  1. VS2010链接TFS遇见错误:TF204017,没有访问工作区域,需要一个或者多个必须权限

    最近刚刚搭建好服务器,然后准备将VSS源代码迁移到TFS源代码管理服务器上面.在我本机先用的服务器帐号来上传初始化源代码数据库,然后我又用自己的帐号进行迁出代码的时候发生的异常. 造成上述错误,主要是 ...

  2. Java int转string 长度不足左补0

    最近项目中用到这个需求,我试了两个方法都可以实现 方法一:(推荐) String s=String.format("%010d", 123)//123为int类型,0代表前面要补的 ...

  3. nodejs sass安装报错一招解决

    背景: 这个问题不是一天两天了,有时候是网速不行,有时候是被墙了,有时候是github把node-sass的包转移目录导致下载失败. Cannot download "https://git ...

  4. 【机器学习算法-python实现】採样算法的简单实现

    1.背景     採样算法是机器学习中比較经常使用,也比較easy实现的(出去分层採样).经常使用的採样算法有下面几种(来自百度知道):     一.单纯随机抽样(simple random samp ...

  5. 迷你音乐播放器v1.0正式上线!

    迷你音乐播放器V1.0正式上线! 版本介绍: 1.随机播放切换开关(通过点击专辑图片) 2.通过拖动歌曲名及艺术家名调整歌曲播放进度 3.手机浏览访问支持熄屏播放 4.暂不支持在线搜索功能 快来一起分 ...

  6. 100个MySQL 的调节和优化的提示

    100个MySQL 的调节和优化的提示 MySQL是一个功能强大的开源数据库.随着越来越多的数据库驱动的应用程序,人们一直在推动MySQL发展到它的极限.这里是101条调节和优化MySQL安装的技巧. ...

  7. C#调用存储过程详解(带返回值、参数输入输出等)

    CREATE PROCEDURE [dbo].[GetNameById] @studentid varchar(8), @studentname nvarchar(50) OUTPUT AS BEGI ...

  8. cmake 常用变量和常用环境变量查表手册---整理 .

    一,cmake 变量引用的方式: 前面我们已经提到了,使用${}进行变量的引用.在 IF 等语句中,是直接使用变量名而不通过${}取值 二,cmake 自定义变量的方式: 主要有隐式定义和显式定义两种 ...

  9. sublime text 3浅色主题

    { // Lighter theme "theme": "Material-Theme-Lighter.sublime-theme", "color_ ...

  10. 【Ubuntu】PHP环境安装-phpstudy for linux版

    安装: wget -c http://lamp.phpstudy.net/phpstudy.bin chmod +x phpstudy.bin    #权限设置sudo ./phpstudy.bin ...