作者 开飞机的舒克

测试七牛云自动上传

@@ -69,8 +69,10 @@ class Demo extends Api @@ -69,8 +69,10 @@ class Demo extends Api
69 */ 69 */
70 public function test3() 70 public function test3()
71 { 71 {
72 -  
73 - 72 + $filepath = ROOT_PATH.'/uploads/barimages/20230317/00000029.png';
  73 + $filename = 'http://rramxwmk1.hb-bkt.clouddn.com/campus1/uploads/20230317/';
  74 + $qinu = $this->qiniu($filepath,$filename);
  75 + $this->success('上传成功',$qinu);
74 } 76 }
75 77
76 } 78 }
@@ -2,6 +2,7 @@ @@ -2,6 +2,7 @@
2 2
3 namespace app\common\controller; 3 namespace app\common\controller;
4 4
  5 +use Qiniu\Auth;
5 use tinymeng\code\Generate; 6 use tinymeng\code\Generate;
6 7
7 class Resource 8 class Resource
@@ -18,5 +19,46 @@ class Resource @@ -18,5 +19,46 @@ class Resource
18 return $file_path; 19 return $file_path;
19 } 20 }
20 21
  22 + /*
  23 + * 七牛云上传
  24 + */
  25 + public function qiniu($filePath = '', $fileName = '')
  26 + {
  27 +// $filePath=ROOT_PATH.'public'.DS.'uploads'.DS.'20200224'.DS.'img1.jpg';//文件路径
  28 +// $fileName='public'.DS.'uploads'.DS.'20200224'.DS.'img1.jpg'; //七牛云上的名字
  29 +// $filePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . '20200224' . DS . 'img2.jpg';//文件路径
  30 +// $fileName = 'public' . DS . 'uploads' . DS . '20200224' . DS . 'img2.jpg'; //七牛云上的名字,头部不带杠
  31 +
  32 + $config = get_addon_config('qiniu');
  33 + $policy = array(
  34 + 'saveKey' => $fileName,
  35 + );
  36 + $auth = new Auth($config['accessKey'], $config['secretKey']);
  37 + $token = $auth->uploadToken($config['bucket'], null, $config['expire'], $policy);
  38 + $multipart = [
  39 + ['name' => 'token', 'contents' => $token],
  40 + [
  41 + 'name' => 'file',
  42 + 'contents' => fopen($filePath, 'r'),
  43 + 'filename' => $fileName,
  44 + ]
  45 + ];
21 46
  47 + try {
  48 + $client = new \GuzzleHttp\Client();
  49 + $res = $client->request('POST', $config['uploadurl'], [
  50 + 'multipart' => $multipart
  51 + ]);
  52 + $code = $res->getStatusCode();
  53 + //成功不做任何操作
  54 + } catch (\GuzzleHttp\Exception\ClientException $e) {
  55 + // unlink($filePath);
  56 + $this->error("上传失败");
  57 + }
  58 +// dump($code);
  59 +// $url = '/';
  60 +
  61 + //上传成功后将存储变更为qiniu
  62 +// $this->success("上传成功", ['url' => cdnurl($url), 'save_path' => $url]);
  63 + }
22 } 64 }