如果你对该文章中的内容有疑问/不解,可以点击此处链接提问
要注明问题和此文章链接地址 点击此处跳转
thinkphp5中使用七牛云
下载 https://github.com/qiniu/php-sdk
vendor文件下
新建文件 application/extra/qiniu.php return [ 'ACCESSKEY' => 'PkQcItX7rJL7',//你的accessKey 'SECRETKEY' => 'eaWM7C_COYLjX8VKVGinzv1',//你的secretKey 'BUCKET' => 'zin',//上传的空间 'DOMAIN'=>'pdn.com'//空间绑定的域名 ];
html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="{:url('test/upload')}" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
php
<?php
namespace app\index\controller;
use think\Config;
use think\Image;
use think\Request;
use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
class Test
{
// 上传
public function test()
{
if(request()->isPost()){
$file = request()->file('image');
// 要上传图片的本地路径
$filePath = $file->getRealPath();
$ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION); //后缀
// 上传到七牛后保存的文件名
$key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
require_once APP_PATH . '/../vendor/qiniu/autoload.php';
// 需要填写你的 Access Key 和 Secret Key
$accessKey = config("qiniu.ACCESSKEY");
$secretKey = config("qiniu.SECRETKEY");
// 构建鉴权对象
$auth = new Auth($accessKey, $secretKey);
// 要上传的空间
$bucket = config("qiniu.BUCKET");
$domain = config("qiniu.DOMAINImage");
$token = $auth->uploadToken($bucket);
// 初始化 UploadManager 对象并进行文件的上传
$uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传
list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
if ($err !== null) {
return json(["err"=>1,"msg"=>$err,"data"=>""]);die;
} else {
//返回图片的完整URL
return json(["err"=>0,"msg"=>"上传完成","data"=>uploadreg($domain . $ret['key'])]);die;
}
}
return view();
}
// 删除
public function delete($name)
{
$delFileName = input("name");
if( $delFileName ==null){
echo "参数不正确";die;
}
require_once APP_PATH . '/../vendor/qiniu/autoload.php';
// 构建鉴权对象
$auth = new Auth(config("qiniu.ACCESSKEY"),config("qiniu.SECRETKEY"));
// 配置
$config = new \Qiniu\Config();
// 管理资源
$bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
// 删除文件操作
$res = $bucketManager->delete(config("qiniu.BUCKET"), $delFileName);
if (is_null($res)) {
// 为null成功
// return true;
echo "成功";
}else{
echo "失败";
}
}
}
?>
王明昌博客
