Beispiel #1
0
 /**
 * 上传文件,要token认证
 * @example shell curl -i -F 'file=@2.jpg' -F 'token=asdf' -F 'key=2.jpg' 'http://up.qiniu.com/' 
 * @example shell ./qrsync ./conf.json
 * @return array array(
        "httpUri" => "http://com-163-sinkcup-test.qiniudn.com/1.jpg",
        "httpsUri" => "https://dn-com-163-sinkcup-test.qbox.me/1.jpg",
    }
 */
 public function uploadFile($localPath, $remoteFileName, $headers = array())
 {
     $remoteFileName = str_replace('/', '', $remoteFileName);
     $uri = 'http://' . str_replace('//', '/', $this->conf['host']['up'] . '/');
     //scope中指定文件,就可以覆盖。如果只写bucket,则重复上传会出现错误:614 文件已存在。
     $policy = array('scope' => $this->bucket . ':' . $remoteFileName, 'deadline' => time() + 3600);
     $pics = array('image/jpeg', 'image/webp', 'image/png');
     //如果是图片,则需要返回分辨率
     if (isset($headers['Content-Type']) && in_array($headers['Content-Type'], $pics)) {
         $policy['returnBody'] = json_encode(array('width' => '$(imageInfo.width)', 'height' => '$(imageInfo.height)'));
     }
     $data = $this->encode(json_encode($policy));
     $token = $this->sign($data) . ':' . $data;
     //$hash = hash_file('crc32b', $localPath);
     //$tmp = unpack('N', pack('H*', $hash));
     $fields = array('token' => $token, 'key' => $remoteFileName);
     $http = new \HTTPRequest($uri, HTTP_METH_POST);
     $contentType = isset($headers['Content-Type']) ? $headers['Content-Type'] : 'multipart/form-data';
     $http->addPostFile('file', $localPath, $contentType);
     $http->addPostFields($fields);
     //$http->setHeader($headers);
     $http->send();
     $body = json_decode($http->getResponseBody(), true);
     $code = $http->getResponseCode();
     if ($code == 200) {
         //自定义域名一定是http,因为证书不能跨域名
         if (!isset($this->conf['customDomain']) || empty($this->conf['customDomain'])) {
             $httpUri = 'http://' . str_replace('//', '/', $this->bucket . $this->conf['httpUriSuffix'] . '/' . $remoteFileName);
         } else {
             $httpUri = 'http://' . $this->conf['customDomain'] . '/' . $remoteFileName;
         }
         $r = array('httpUri' => $httpUri, 'httpsUri' => 'https://' . str_replace('//', '/', $this->conf['httpsUriPrefix'] . $this->bucket . $this->conf['httpsUriSuffix'] . '/' . $remoteFileName));
         if (isset($body['width'])) {
             $r['width'] = $body['width'];
         }
         if (isset($body['height'])) {
             $r['height'] = $body['height'];
         }
         return $r;
     }
     throw new Exception($body['error'], $code);
 }