thinkphp5中使用七牛云
下载 https://github.com/qiniu/php-sdk
vendor文件下
1 新建文件 application/extra/qiniu.php 2 return [ 3 'ACCESSKEY' => 'PkQcItX7rJL7',//你的accessKey 4 'SECRETKEY' => 'eaWM7C_COYLjX8VKVGinzv1',//你的secretKey 5 'BUCKET' => 'zin',//上传的空间 6 'DOMAIN'=>'pdn.com'//空间绑定的域名 7 ];
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
1 <?php 2 namespace appindexcontroller; 3 use thinkConfig; 4 use thinkImage; 5 use thinkRequest; 6 use QiniuAuth as Auth; 7 use QiniuStorageBucketManager; 8 use QiniuStorageUploadManager; 9 10 class Test 11 { 12 // 上传 13 public function test() 14 { 15 if(request()->isPost()){ 16 $file = request()->file('image'); 17 // 要上传图片的本地路径 18 $filePath = $file->getRealPath(); 19 $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION); //后缀 20 21 // 上传到七牛后保存的文件名 22 $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext; 23 require_once APP_PATH . '/../vendor/qiniu/autoload.php'; 24 // 需要填写你的 Access Key 和 Secret Key 25 $accessKey = config("qiniu.ACCESSKEY"); 26 $secretKey = config("qiniu.SECRETKEY"); 27 // 构建鉴权对象 28 $auth = new Auth($accessKey, $secretKey); 29 // 要上传的空间 30 $bucket = config("qiniu.BUCKET"); 31 $domain = config("qiniu.DOMAINImage"); 32 $token = $auth->uploadToken($bucket); 33 // 初始化 UploadManager 对象并进行文件的上传 34 $uploadMgr = new UploadManager(); 35 // 调用 UploadManager 的 putFile 方法进行文件的上传 36 list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath); 37 if ($err !== null) { 38 return json(["err"=>1,"msg"=>$err,"data"=>""]);die; 39 } else { 40 //返回图片的完整URL 41 return json(["err"=>0,"msg"=>"上传完成","data"=>uploadreg($domain . $ret['key'])]);die; 42 } 43 } 44 return view(); 45 } 46 47 // 删除 48 public function delete($name) 49 { 50 $delFileName = input("name"); 51 if( $delFileName ==null){ 52 echo "参数不正确";die; 53 } 54 require_once APP_PATH . '/../vendor/qiniu/autoload.php'; 55 // 构建鉴权对象 56 $auth = new Auth(config("qiniu.ACCESSKEY"),config("qiniu.SECRETKEY")); 57 58 // 配置 59 $config = new QiniuConfig(); 60 61 // 管理资源 62 $bucketManager = new QiniuStorageBucketManager($auth, $config); 63 64 // 删除文件操作 65 $res = $bucketManager->delete(config("qiniu.BUCKET"), $delFileName); 66 67 if (is_null($res)) { 68 // 为null成功 69 // return true; 70 echo "成功"; 71 }else{ 72 echo "失败"; 73 } 74 } 75 76 77 } 78 79 ?>