PHP上传文件及图片到七牛的方法

这篇文章主要介绍了PHP上传文件及图片到七牛的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧。

上传文件到七牛最简单的方式就是使用七牛官方最新的SDK

安装PHP SDK

composer require qiniu/php-sdk

上传文件到七牛

  1. use Qiniu\Auth;
  2. use Qiniu\Storage\UploadManager;
  3. $cfg = [
  4. 'access' => 'YOUR_ACCESS_KEY',
  5. 'secret' => 'YOUR_SECRET_KEY',
  6. 'bucket' => 'YOUR_BUCKET',
  7. 'domain' => 'https://images.your_domain.com'
  8. ];
  9. $auth = new Auth($cfg['access'], $cfg['secret']);
  10. // 创建一个过期时间为1小时的临时上传令牌
  11. $token = $auth->uploadToken($cfg['bucket'], null, 3600);
  12. $filePath = "./illustration.png";
  13. $uploadMgr = new UploadManager();
  14. list($ret, $err) = $uploadMgr->putFile($token, null, $filePath);
  15. if($err !== null) {
  16. $this->err = $err;
  17. } else {
  18. echo $cfg['domain'] . '/' . $ret['key'];
  19. }

php向七牛上传base64编码的图片

与大家分享一下我的代码:

  1. <?php
  2. require_once 'vendor/autoload.php';
  3. header('Access-Control-Allow-Origin:*');
  4. use Qiniu\Auth;
  5. $bucket = '要上传的空间名';
  6. $accessKey = '你的accessKey';
  7. $secretKey = '你的secretKey';
  8. $auth = new Auth($accessKey, $secretKey);
  9. $upToken = $auth->uploadToken($bucket, null, 3600);//获取上传所需的token
  10. function request_by_curl($remote_server,$post_string,$upToken) {
  11. $headers = array();
  12. $headers[] = 'Content-Type:image/png';
  13. $headers[] = 'Authorization:UpToken '.$upToken;
  14. $ch = curl_init();
  15. curl_setopt($ch, CURLOPT_URL,$remote_server);
  16. //curl_setopt($ch, CURLOPT_HEADER, 0);
  17. curl_setopt($ch, CURLOPT_HTTPHEADER ,$headers);
  18. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  19. //curl_setopt($ch, CURLOPT_POST, 1);
  20. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
  21. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  22. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  23. $data = curl_exec($ch);
  24. curl_close($ch);
  25. return $data;
  26. }
  27. $str="base64编码的字符串";
  28. echo "<pre>";
  29. echo request_by_curl('http://upload.qiniu.com/putb64/-1',$str,$upToken);
  30. echo "</pre>";