Lite.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * 七牛接口调用
  4. * 1、图片文件上传
  5. *
  6. * 参考:http://developer.qiniu.com/docs/v6/sdk/php-sdk.html
  7. *
  8. * @author: dogstar 2015-03-17
  9. */
  10. require_once dirname(__FILE__) . '/qiniu/io.php';
  11. require_once dirname(__FILE__) . '/qiniu/rs.php';
  12. class Qiniu_Lite {
  13. protected $config;
  14. /**
  15. * @param string $config['accessKey'] 统一的key
  16. * @param string $config['secretKey']
  17. * @param string $config['space_bucket'] 自定义配置的空间
  18. * @param string $config['space_host']
  19. */
  20. public function __construct($config = NULL) {
  21. $this->config = $config;
  22. if ($this->config === NULL) {
  23. $this->config = DI()->config->get('app.Qiniu');
  24. }
  25. }
  26. /**
  27. * 文件上传
  28. * @param string $filePath 待上传文件的绝对路径
  29. * @return string 上传成功后的URL,失败时返回空
  30. */
  31. public function uploadFile($filePath)
  32. {
  33. $fileUrl = '';
  34. if (!file_exists($filePath)) {
  35. return $fileUrl;
  36. }
  37. $config = $this->config;
  38. $fileName = date('YmdHis_', $_SERVER['REQUEST_TIME'])
  39. . md5(PhalApi_Tool::createRandStr(8) . microtime(true));
  40. Qiniu_SetKeys($config['accessKey'], $config['secretKey'], $config['uphost']);
  41. $putPolicy = new Qiniu_RS_PutPolicy($config['space_bucket']);
  42. $upToken = $putPolicy->Token(null);
  43. $putExtra = new Qiniu_PutExtra();
  44. $putExtra->Crc32 = 1;
  45. list($ret, $err) = Qiniu_PutFile($upToken, $fileName, $filePath, $putExtra);
  46. if ($err !== null) {
  47. DI()->logger->debug('failed to upload file to qiniu',
  48. array('Err' => $err->Err, 'Reqid' => $err->Reqid, 'Details' => $err->Details, 'Code' => $err->Code));
  49. } else {
  50. $fileUrl = $config['space_host'] . '/' . $fileName;
  51. DI()->logger->debug('succeed to upload file to qiniu', $ret);
  52. }
  53. return $fileUrl;
  54. }
  55. /**
  56. * 获取七牛Token
  57. * @return string 七牛Token
  58. */
  59. public function getQiniuToken()
  60. {
  61. $config = $this->config;
  62. Qiniu_SetKeys($config['accessKey'], $config['secretKey']);
  63. $putPolicy = new Qiniu_RS_PutPolicy($config['space_bucket']);
  64. $upToken = $putPolicy->Token(null);
  65. return $upToken;
  66. }
  67. /**
  68. * 获取七牛Token(方法重写)
  69. * @return string 七牛Token
  70. */
  71. public function getQiniuToken2($accesskey,$secretkey,$bucket){
  72. Qiniu_SetKeys($accesskey, $secretkey);
  73. $putPolicy = new Qiniu_RS_PutPolicy($bucket);
  74. $upToken = $putPolicy->Token(null);
  75. return $upToken;
  76. }
  77. }