功能
输入框中填入:bucket Access Key 和 Secret Key
点击提交后,向七牛服务器认证,若认证通过,则在当前页面动态刷新,刚才的输入框消失。
显示一个上传文件按钮,点击可继续添加文件(最多同时上传5个)。文件的key为yyy-mm-dd-hh-name.xxx
然后提交文件后显示进度条,并在下面动态回显上传文件的结果以及文件的url。
七牛API
上传策略
{
"scope": "<Bucket string>",
"deadline": <UnixTimestamp int64>,
"endUser": "<EndUserId string>",
"returnUrl": "<RedirectURL string>",
"returnBody": "<ResponseBodyForAppClient string>",
"callbackBody": "<RequestBodyForAppServer string>",
"callbackUrl": "<RequestUrlForAppServer string>",
"persistentOps": "<persistentOpsCmds string>",
"persistentNotifyUrl": "<persistentNotifyUrl string>",
"insertOnly": "<AllowFileUpdating uint16>",
"detectMime": "<AutoDetectMimeType uint16>",
"fsizeLimit": "<FileSizeLimit int64>",
"saveKey": "<KeyFomart string>",
"mimeLimit": "<MimeLimit string>"
}
其中scope和deadline为必选。
上传凭证
1.构造上传策略
2.将上传策略序列化成为JSON格式
3.对JSON编码的上传策略进行URL安全的Base64编码,得到待签名字符串:
encodedPutPolicy = urlsafe_base64_encode(putPolicy)
4.使用SecertKey对上一步生成的待签名字符串计算HMAC-SHA1签名
sign = hmac_sha1(signingStr, "<SecretKey>")
5.对签名进行URL安全的Base64编码:
encodedSign = urlsafe_base64_encode(sign)
6.将AccessKey、encodedSign和encodedPutPolicy用:连接起来:
uploadToken = AccessKey + ':' + encodedSign + ':' + encodedPutPolicy
表单上传(POST方式)
<form method="post" action="http://up.qiniu.com/"
enctype="multipart/form-data">
<input name="key" type="hidden" value="<resource_key>">
<input name="x:<custom_name>" type="hidden" value="<custom_value>">
<input name="token" type="hidden" value="<upload_token>">
<input name="file" type="file" />
</form>
token和file为必选,token指的是上传凭证,file为文件本身
反馈
PHP实现
服务端生成上传凭证
require_once("qiniu/rs.php");
$bucket = 'phpsdk';
$accessKey = '<YOUR_APP_ACCESS_KEY>';
$secretKey = '<YOUR_APP_SECRET_KEY>';
Qiniu_SetKeys($accessKey, $secretKey);
$putPolicy = new Qiniu_RS_PutPolicy($bucket);
$upToken = $putPolicy->Token(null);
上传本地文件
require_once("qiniu/io.php");
require_once("qiniu/rs.php");
$bucket = "phpsdk";
$key1 = "file_name1";
$accessKey = '<YOUR_APP_ACCESS_KEY>';
$secretKey = '<YOUR_APP_SECRET_KEY>';
Qiniu_SetKeys($accessKey, $secretKey);
$putPolicy = new Qiniu_RS_PutPolicy($bucket);
$upToken = $putPolicy->Token(null);
$putExtra = new Qiniu_PutExtra();
$putExtra->Crc32 = 1;
list($ret, $err) = Qiniu_PutFile($upToken, $key1, __file__, $putExtra);
echo "====> Qiniu_PutFile result: \n";
if ($err !== null) {
var_dump($err);
} else {
var_dump($ret);
}
参考
[1]:http://developer.qiniu.com/docs/v6/api/reference/security/upload-token.html
[2]:http://developer.qiniu.com/docs/v6/api/reference/security/put-policy.html
来源:oschina
链接:https://my.oschina.net/u/1171834/blog/195278