MyCurlFile.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | WeChatDeveloper
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2014~2023 ThinkAdmin [ thinkadmin.top ]
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: https://thinkadmin.top
  8. // +----------------------------------------------------------------------
  9. // | 开源协议 ( https://mit-license.org )
  10. // | 免责声明 ( https://thinkadmin.top/disclaimer )
  11. // +----------------------------------------------------------------------
  12. // | gitee 代码仓库:https://gitee.com/zoujingli/WeChatDeveloper
  13. // | github 代码仓库:https://github.com/zoujingli/WeChatDeveloper
  14. // +----------------------------------------------------------------------
  15. namespace WeChat\Contracts;
  16. /**
  17. * 自定义CURL文件类
  18. * Class MyCurlFile
  19. * @package WeChat\Contracts
  20. */
  21. class MyCurlFile extends \stdClass
  22. {
  23. /**
  24. * 当前数据类型
  25. * @var string
  26. */
  27. public $datatype = 'MY_CURL_FILE';
  28. /**
  29. * MyCurlFile constructor.
  30. * @param string|array $filename
  31. * @param string $mimetype
  32. * @param string $postname
  33. * @throws \WeChat\Exceptions\LocalCacheException
  34. */
  35. public function __construct($filename, $mimetype = '', $postname = '')
  36. {
  37. if (is_array($filename)) {
  38. foreach ($filename as $k => $v) $this->{$k} = $v;
  39. } else {
  40. $this->mimetype = $mimetype;
  41. $this->postname = $postname;
  42. $this->extension = pathinfo($filename, PATHINFO_EXTENSION);
  43. if (empty($this->extension)) $this->extension = 'tmp';
  44. if (empty($this->mimetype)) $this->mimetype = Tools::getExtMine($this->extension);
  45. if (empty($this->postname)) $this->postname = pathinfo($filename, PATHINFO_BASENAME);
  46. $this->content = base64_encode(file_get_contents($filename));
  47. $this->tempname = md5($this->content) . ".{$this->extension}";
  48. }
  49. }
  50. /**
  51. * 获取文件上传信息
  52. * @return \CURLFile|string
  53. * @throws \WeChat\Exceptions\LocalCacheException
  54. */
  55. public function get()
  56. {
  57. $this->filename = Tools::pushFile($this->tempname, base64_decode($this->content));
  58. if (class_exists('CURLFile')) {
  59. return new \CURLFile($this->filename, $this->mimetype, $this->postname);
  60. } else {
  61. return "@{$this->tempname};filename={$this->postname};type={$this->mimetype}";
  62. }
  63. }
  64. /**
  65. * 通用销毁函数清理缓存文件
  66. * 提前删除过期因此放到了网络请求之后
  67. */
  68. public function __destruct()
  69. {
  70. // Tools::delCache($this->tempname);
  71. }
  72. }