12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- <?php
- namespace Upload\Lib\View;
- use Dever;
- Dever::apply('sdk/sina', 'upload');
- class Sina
- {
- private $client;
- private $token;
- private $auth;
- private $bucket;
- # 连接
- public function connect($config, $upload, $file = null)
- {
- $this->auth = new \SCS($config['appkey'], $config['appsecret']);
- $this->auth->setExceptions(true);
- $this->bucket = $upload['bucket'];
- return $this;
- }
- # 删除文件
- public function delete($file, $bucket = false)
- {
- $bucket = $bucket ? $bucket : $this->bucket;
- $result = $this->auth->deleteObject($bucket, $file);
- return $result;
- }
- # 下载文件
- public function download($bucket, $file, $local = false)
- {
- $temp_file = tempnam(sys_get_temp_dir(), 'Tux');
- $ret = $this->auth->getObject($bucket, $file, $temp_file);
- $content = file_get_contents($temp_file);
- return $content;
- }
- # 上传文件
- public function upload($file, $source_file, $options = array(), $base64 = false)
- {
- try {
- if ($base64) {
- $ret = $this->auth->putObject($source_file, $this->bucket, $file, \SCS::ACL_PUBLIC_READ, array(), array('Content-Type' => 'text/plain'));
- } elseif (strstr($source_file, 'http')) {
- $source_file = file_get_contents($source_file);
- $ret = $this->auth->putObject($source_file, $this->bucket, $file, \SCS::ACL_PUBLIC_READ, array(), array('Content-Type' => 'text/plain'));
- } else {
- //$ret = $this->auth->putObject($this->auth->inputFile($source_file, false), $this->bucket, $file, \SCS::ACL_PUBLIC_READ);
- //初始化上传
- $info = $this->auth->initiateMultipartUpload($this->bucket, $file, \SCS::ACL_PUBLIC_READ);
- $uploadId = $info['upload_id'];
- $fp = fopen($source_file, 'rb');
- $i = 1;
- $part_info = array();
- while (!feof($fp)) {
- /*上传分片,一个分片512KB*/
- $res = $this->auth->putObject($this->auth->inputResourceMultipart($fp, 1024 * 512, $uploadId, $i), $this->bucket, $file);
- if (isset($res['hash'])) {
- $part_info[] = array(
- 'PartNumber' => $i,
- 'ETag' => $res['hash'],
- );
- }
- $i++;
- }
- //列分片
- $parts = $this->auth->listParts($this->bucket, $file, $uploadId);
- if (count($parts) > 0 && count($parts) == count($part_info)) {
- foreach ($parts as $part_number => $part) {
- if ($part['etag'] != $part_info[$part_number - 1]['ETag']) {
- Dever::alert('上传失败');
- break;
- }
- }
- //合并分片
- $this->auth->completeMultipartUpload($this->bucket, $file, $uploadId, $part_info);
- fclose($fp);
- }
- $ret = true;
- }
- } catch (\SCSException $e) {
- Dever::alert('上传失败:' . $e->getMessage());
- }
- return $ret;
- }
- }
|