设置了callbackUrl,七牛只是在客户端上打印了json格式的key和hash,居然没有按照设置跳转回来..怎么弄?

文件是上传成功了,但是就停了,咩有按照设置的callbackUrl跳转,我只是想上传之后七牛返回Location字段为我设置的URl,并且带post或get,好让我把上传文件信息插入数据库,还有callbackBody和returnBody除有什么区别?感激不尽..
clipboard.png

clipboard.png

flag和表单代码如下:(隐藏了accesskey还有srcretkey)

<? print_r($_POST);
$client = new QiniuClient($accessKey,$secretKey);
$flag = array('scope'=>'help', 'saveKey'=> 'kdfsufes6asdawes4ks.zip','callbackUrl '=> '"http://6.ncic.sinaapp.com/"', 'callbackBody' => '"name": $(fname),
  "size": $(fsize),
  "w": $(imageInfo.width),
  "h": $(imageInfo.height),
  "hash": $(etag),');


//print_r($client); 

//print $token;print $access_token;

?>


<form method="post" action="http://upload.qiniu.com/"
 enctype="multipart/form-data">
  
  <input name="x:<custom_name>" type="hidden" value="<custom_value>">
  <input name="token" type="hidden" value="<? echo  $client->uploadToken($flag);?>">
  <input name="file" type="file" />
 
  <input name="accept" type="hidden" />
     <input type="submit" />
</form>


include的内容

<?php

class QiniuClient
{
    const UP_HOST = 'http://up.qiniu.com';
    const RS_HOST = 'http://rs.qbox.me';
    const RSF_HOST = 'http://rsf.qbox.me';

    public $accessKey;
    public $secretKey;

    function __construct($accessKey='',$secretKey='')
    {
        $this->accessKey = $accessKey;
        $this->secretKey = $secretKey;
    }

    public function uploadFile($filePath,$bucket,$key=null)
    {
        $uploadToken = $this->uploadToken(array('scope' => $bucket));
        $data = array();
        $data['file'] = "@$filePath";
        $data['token'] = $uploadToken;
        if($key) $data['key'] = $key;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::UP_HOST);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function upload($content,$bucket,$key=null)
    {
        $filePath = tempnam(sys_get_temp_dir(), 'UPLOAD');
        file_put_contents($filePath, $content);
        $result = $this->uploadFile($filePath,$bucket,$key);
        unlink($filePath);
        return $result;
    }

    public function uploadRemote($url,$bucket,$key=null)
    {
        $filePath = tempnam(sys_get_temp_dir(), 'UPLOAD');
        copy($url,$filePath);
        $result = $this->uploadFile($filePath,$bucket,$key);
        unlink($filePath);
        return $result;
    }

    public function stat($bucket,$key)
    {
        $encodedEntryURI = self::urlsafe_base64_encode("{$bucket}:{$key}");
        $url = "/stat/{$encodedEntryURI}";
        return $this->fileHandle($url);
    }

    public function move($bucket,$key,$bucket2,$key2=false)
    {
        if(!$key2) {
            $key2 = $bucket2;
            $bucket2 = $bucket;
        }
        $encodedEntryURISrc = self::urlsafe_base64_encode("{$bucket}:{$key}");
        $encodedEntryURIDest = self::urlsafe_base64_encode("{$bucket2}:{$key2}");
        $url = "/move/{$encodedEntryURISrc}/{$encodedEntryURIDest}";
        return $this->fileHandle($url);
    }

    public function copy($bucket,$key,$bucket2,$key2=false)
    {
        if(!$key2) {
            $key2 = $bucket2;
            $bucket2 = $bucket;
        }
        $encodedEntryURISrc = self::urlsafe_base64_encode("{$bucket}:{$key}");
        $encodedEntryURIDest = self::urlsafe_base64_encode("{$bucket2}:{$key2}");
        $url = "/copy/{$encodedEntryURISrc}/{$encodedEntryURIDest}";
        return $this->fileHandle($url);
    }

    public function delete($bucket,$key)
    {
        $encodedEntryURI = self::urlsafe_base64_encode("{$bucket}:{$key}");
        $url = "/delete/{$encodedEntryURI}";
        return $this->fileHandle($url);
    }

    // $operator = stat|move|copy|delete 
    // $client->batch('stat',array('square:test/test5.txt','square:test/test13.png'));
    public function batch($operator,$files)
    {
        $data = '';
        foreach ($files as $file) {
            if(!is_array($file)) {
                $encodedEntryURI = self::urlsafe_base64_encode($file);
                $data.="op=/{$operator}/{$encodedEntryURI}&";
            }else{
                $encodedEntryURI = self::urlsafe_base64_encode($file[0]);
                $encodedEntryURIDest = self::urlsafe_base64_encode($file[1]);
                $data.="op=/{$operator}/{$encodedEntryURI}/{$encodedEntryURIDest}&";
            }
        }
        return $this->fileHandle('/batch',$data);
    }

    public function listFiles($bucket,$limit='',$prefix='',$marker='')
    {
        $params = array_filter(compact('bucket','limit','prefix','marker'));
        $url = self::RSF_HOST.'/list?'.http_build_query($params);
        return $this->fileHandle($url);
    }

    public function fileHandle($url,$data=array())
    {
        if(strpos($url, 'http://')!==0) $url = self::RS_HOST.$url;

        if(is_array($data)) $accessToken = $this->accessToken($url);
        else $accessToken = $this->accessToken($url,$data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Authorization: QBox '.$accessToken,
        ));

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        // If $data is an array, the Content-Type header will be set to multipart/form-data
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        if($info['http_code']>=300)
            throw new Exception($info['http_code'].': '.$result);
        if($info['content_type']=='application/json')
            return json_decode($result,true);

        return $result;
    }

    public function uploadToken($flags)
    {
        if(!isset($flags['deadline']))
            $flags['deadline'] = 3600 + time();
        $encodedFlags = self::urlsafe_base64_encode(json_encode($flags));
        $sign = hash_hmac('sha1', $encodedFlags, $this->secretKey, true);
        $encodedSign = self::urlsafe_base64_encode($sign);
        $token = $this->accessKey.':'.$encodedSign. ':' . $encodedFlags;
        return $token;
    }

    public function accessToken($url,$body=false){
        $parsed_url = parse_url($url);
        $path = $parsed_url['path'];
        $access = $path;
        if (isset($parsed_url['query'])) {
            $access .= "?" . $parsed_url['query'];
        }
        $access .= "\n";
        if($body) $access .= $body;
        $digest = hash_hmac('sha1', $access, $this->secretKey, true);
        return $this->accessKey.':'.self::urlsafe_base64_encode($digest);
    }

    public static function urlsafe_base64_encode($str){
        $find = array("+","/");
        $replace = array("-", "_");
        return str_replace($find, $replace, base64_encode($str));
    }
}
阅读 4.7k
2 个回答

详细文档可以参考 http://developer.qiniu.com/docs/v6/api/reference/security/put-policy.h...

callbackUrl一般是业务服务器的地址,需要是公网可访的一个可以接受post请求的url,而post给callbackUrl的内容是callbackBody指定的内容,一旦设置了callbackUrl,那么上传端收到的内容就是业务服务器响应七牛的回调的内容,所以此时设置returnBody没有效果;

在没有设置returnUrlcallbackUrl的时候,设置了returnBody,那么上传端在上传七牛之后,七牛则会直接收到returnBody中设置的json串,但是此时业务服务器不会感知到客户端的上传;

如果设置了returnUrl,那么returnBody会出现在上传后进行302跳转的returnUrl的参数列表中。

新手上路,请多包涵

我的问题已解决,给大家附送成功上传并获返回值的可使用代码,结果存在了$upload_ret(是我这个还是个高中生写的..><您们肯信的过就用),前提是只需引用一个function相关文件,(不好意思我php是放寒假直接自学英文版本,没有工作经验..很多中文不知怎么说),可以是require或include(其实无什么所谓,后来已经Pubilc),代码是当时、一步一步实现、调试,又懒得改,所以,还有几行无用的甚至可简化为一行,但不影响使用,也方便让你们看懂。可自行优化见代码:

<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<?
 /*
function urlsafe_b64decode($string) {
   $data = str_replace(array('-','_'),array('+','/'),$string);
   $mod4 = strlen($data) % 4;
   if ($mod4) {
       $data .= substr('====', $mod4);
   }
   return base64_decode($data);
 }*/
//print_r($_POST);
//echo $_GET['upload_ret'];
$upload_ret = $_GET['upload_ret'];
$upload_ret =  urlsafe_b64decode($upload_ret);
$upload_ret_length =  strlen($upload_ret) - 3;
//echo $upload_ret_length;
$upload_ret = substr($upload_ret , 0 , $upload_ret_length) . ' }';
//print $upload_ret;
$upload_ret = json_decode($upload_ret,true);
//print $upload_ret;
print_r($upload_ret);
if(isset($_POST))   {
$mysql = new SaeMysql();
$sql = "INSERT  INTO `temp` ( `id`,`content`) VALUES ('"  . 0 . "' , '" . $content . "' ) ";
    $mysql->runSql($sql); }
include 'QiniuClient.php';
$accessKey = '你的Key';
$secretKey = '<你的key>';
$client = new QiniuClient($accessKey,$secretKey);
$flag = array('scope'=>'help', 'saveKey'=> 'kcsdsshhhssl.zip','returnUrl'=> 'http://你设置个地址', 'returnBody' => '{
  "name": $(fname),
  "key": $(key),
  "size": $(fsize),
  "w": $(imageInfo.width),
  "h": $(imageInfo.height),
  "hash": $(etag),
}');


//print_r($client); 

//print $token;print $access_taoken;

?>


<form method="post" action="http://upload.qiniu.com/"
 enctype="multipart/form-data">
  

  <input name="token" type="hidden" value="<? echo  $client->uploadToken($flag);?>">
  <input name="file" type="file" />
 
  <input name="accept" type="hidden" />
     <input type="submit" />
</form>


//自行引用此下面内容文件,代码一杯 
<?php

class QiniuClient
{
    const UP_HOST = 'http://up.qiniu.com';
    const RS_HOST = 'http://rs.qbox.me';
    const RSF_HOST = 'http://rsf.qbox.me';

    public $accessKey;
    public $secretKey;

    function __construct($accessKey='',$secretKey='')
    {
        $this->accessKey = $accessKey;
        $this->secretKey = $secretKey;
    }

    public function uploadFile($filePath,$bucket,$key=null)
    {
        $uploadToken = $this->uploadToken(array('scope' => $bucket));
        $data = array();
        $data['file'] = "@$filePath";
        $data['token'] = $uploadToken;
        if($key) $data['key'] = $key;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::UP_HOST);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function upload($content,$bucket,$key=null)
    {
        $filePath = tempnam(sys_get_temp_dir(), 'UPLOAD');
        file_put_contents($filePath, $content);
        $result = $this->uploadFile($filePath,$bucket,$key);
        unlink($filePath);
        return $result;
    }

    public function uploadRemote($url,$bucket,$key=null)
    {
        $filePath = tempnam(sys_get_temp_dir(), 'UPLOAD');
        copy($url,$filePath);
        $result = $this->uploadFile($filePath,$bucket,$key);
        unlink($filePath);
        return $result;
    }

    public function stat($bucket,$key)
    {
        $encodedEntryURI = self::urlsafe_base64_encode("{$bucket}:{$key}");
        $url = "/stat/{$encodedEntryURI}";
        return $this->fileHandle($url);
    }

    public function move($bucket,$key,$bucket2,$key2=false)
    {
        if(!$key2) {
            $key2 = $bucket2;
            $bucket2 = $bucket;
        }
        $encodedEntryURISrc = self::urlsafe_base64_encode("{$bucket}:{$key}");
        $encodedEntryURIDest = self::urlsafe_base64_encode("{$bucket2}:{$key2}");
        $url = "/move/{$encodedEntryURISrc}/{$encodedEntryURIDest}";
        return $this->fileHandle($url);
    }

    public function copy($bucket,$key,$bucket2,$key2=false)
    {
        if(!$key2) {
            $key2 = $bucket2;
            $bucket2 = $bucket;
        }
        $encodedEntryURISrc = self::urlsafe_base64_encode("{$bucket}:{$key}");
        $encodedEntryURIDest = self::urlsafe_base64_encode("{$bucket2}:{$key2}");
        $url = "/copy/{$encodedEntryURISrc}/{$encodedEntryURIDest}";
        return $this->fileHandle($url);
    }

    public function delete($bucket,$key)
    {
        $encodedEntryURI = self::urlsafe_base64_encode("{$bucket}:{$key}");
        $url = "/delete/{$encodedEntryURI}";
        return $this->fileHandle($url);
    }

    // $operator = stat|move|copy|delete 
    // $client->batch('stat',array('square:test/test5.txt','square:test/test13.png'));
    public function batch($operator,$files)
    {
        $data = '';
        foreach ($files as $file) {
            if(!is_array($file)) {
                $encodedEntryURI = self::urlsafe_base64_encode($file);
                $data.="op=/{$operator}/{$encodedEntryURI}&";
            }else{
                $encodedEntryURI = self::urlsafe_base64_encode($file[0]);
                $encodedEntryURIDest = self::urlsafe_base64_encode($file[1]);
                $data.="op=/{$operator}/{$encodedEntryURI}/{$encodedEntryURIDest}&";
            }
        }
        return $this->fileHandle('/batch',$data);
    }

    public function listFiles($bucket,$limit='',$prefix='',$marker='')
    {
        $params = array_filter(compact('bucket','limit','prefix','marker'));
        $url = self::RSF_HOST.'/list?'.http_build_query($params);
        return $this->fileHandle($url);
    }

    public function fileHandle($url,$data=array())
    {
        if(strpos($url, 'http://')!==0) $url = self::RS_HOST.$url;

        if(is_array($data)) $accessToken = $this->accessToken($url);
        else $accessToken = $this->accessToken($url,$data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Authorization: QBox '.$accessToken,
        ));

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        // If $data is an array, the Content-Type header will be set to multipart/form-data
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        if($info['http_code']>=300)
            throw new Exception($info['http_code'].': '.$result);
        if($info['content_type']=='application/json')
            return json_decode($result,true);

        return $result;
    }

    public function uploadToken($flags)
    {
        if(!isset($flags['deadline']))
            $flags['deadline'] = 3600 + time();

        $encodedFlags = self::urlsafe_base64_encode(str_replace("\\/", "/",  json_encode($flags)));
        $sign = hash_hmac('sha1', $encodedFlags, $this->secretKey, true);
        $encodedSign = self::urlsafe_base64_encode($sign);
        $token = $this->accessKey.':'.$encodedSign. ':' . $encodedFlags;
        return $token;
    }

    public function accessToken($url,$body=false){
        $parsed_url = parse_url($url);
        $path = $parsed_url['path'];
        $access = $path;
        if (isset($parsed_url['query'])) {
            $access .= "?" . $parsed_url['query'];
        }
        $access .= "\n";
        if($body) $access .= $body;
        $digest = hash_hmac('sha1', $access, $this->secretKey, true);
        return $this->accessKey.':'.self::urlsafe_base64_encode($digest);
    }

    public static function urlsafe_base64_encode($str){
        $find = array("+","/");
        $replace = array("-", "_");
        return str_replace($find, $replace, base64_encode($str));
    }
}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进