1.下载七牛云的接口文件
使用tp去上传文件至七牛云,首先需要使用七牛云提供的php的sdk ,有两种方式
1.直接去七牛云的官网下载
传送门 https://developer.qiniu.com/kodo/sdk/1241/php
2.下载composer,使用这个包管理工具进行下载(推荐)
这个比较简单,先去官网下载安装包即可 ,传送门
https://getcomposer.org/download/
安装网上教程很多坑,按照这个大神的就ok了 传送门 https://www.1949idc.com/shownews580.html
安装完毕后就可以一行命令安装了七牛云的sdk
官网传送门如下 http://www.thinkphp.cn/topic/57473.html
2.去七牛云去配置相关存储空间
传送门 https://jingyan.baidu.com/article/0bc808fc267b8f1bd485b93b.html
注意,你要得到4个参数才能使用php去链接七牛云的服务器
AccessKey / SecretKey
这两个去 个人面板>密钥管理中可以找到
bucket
就是你新建的存储空间的名字
domain
就是你最后生成的公网地址的前缀,就是你的外链默认域名
坑坑坑
重要的事情说三遍,这里有个大坑,因为你的七牛云可能会有两套密钥,一定要两套密钥都试一遍!!!
3.在控制器内引用依赖文件
require_once APP_PATH . ‘…/vendor/qiniu/php-sdk/autoload.php’;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Qiniu;
4.编写文件上传代码
public function up_load($file)
{
//接受参 数
$filePath = $file->getRealPath();
e x t = p a t h i n f o ( ext = pathinfo( ext=pathinfo(file->getInfo(‘name’), PATHINFO_EXTENSION);
//获取当前控制器名称
$controllerName = ‘index’;
// 上传到七牛后保存的文件名
k e y = d a t e ( ′ Y m d ′ ) . ′ / ′ . s u b s t r ( m d 5 ( key =date('Ymd') .'/'.substr(md5( key=date(′Ymd′).′/′.substr(md5(file->getRealPath()) , 0, 5). rand(0, 9999) . ‘.’ . $ext;
// 需要填写你的 Access Key 和 Secret Key
$accessKey = ‘你的ac’;
$secretKey = ‘你的sc’;
// 构建鉴权对象
a u t h = n e w A u t h ( auth = new Auth( auth=newAuth(accessKey, $secretKey);
// 要上传的空间
$bucket = '你的’对象存储空间名;
$domain = ‘你的默认链接地址’;
$token = a u t h − > u p l o a d T o k e n ( auth->uploadToken( auth−>uploadToken(bucket);
// 初始化 UploadManager 对象并进行文件的上传
u p l o a d M g r = n e w U p l o a d M a n a g e r ( ) ; / / 调 用 U p l o a d M a n a g e r 的 p u t F i l e 方 法 进 行 文 件 的 上 传 l i s t ( uploadMgr = new UploadManager(); // 调用 UploadManager 的 putFile 方法进行文件的上传 list( uploadMgr=newUploadManager();//调用UploadManager的putFile方法进行文件的上传list(ret, $err) = u p l o a d M g r − > p u t F i l e ( uploadMgr->putFile( uploadMgr−>putFile(token, $key, f i l e P a t h ) ; i f ( filePath); if ( filePath);if(err !== null) {
return false;
} else {
//返回图片的完整URL
r e t [ ′ k e y ′ ] = s t r r e p l a c e ( ′ ′ , ′ / ′ , ret['key'] = str_replace('\\','/', ret[′key′]=strreplace(′′,′/′,ret[‘key’]);
return $ret[‘key’];
}
}