一、官方参考文档:
1.上传策略http://developer.qiniu.com/article/developer/security/put-policy.html
2.上传凭证(即uptoken)http://developer.qiniu.com/article/developer/security/upload-token.html
3.下载凭证http://developer.qiniu.com/article/developer/security/download-token.html
4.token生成在线演示http://jsfiddle.net/gh/get/extjs/4.2/icattlecoder/jsfiddle/tree/master/uptoken
二:生成token
1.首先,我在七牛开辟了一个公共的存储空间名为:images
生成token的方法是:
第一步:确定上策略
第二步:将上传策略序列化为json格式
{"scope":"你的bucket","deadline":有效时间,默认是一个小时}
第三步:对json序列化后的上传策略进行URL安全的Base64编码,得到encoded
第四步:用SecretKey对编码后的上传策略进行HMAC-SHA1加密,并且做URL安全的Base64编码,得到encoded_signed
第五步:将 AccessKey、encode_signed 和 encoded 用 “:” 连接起来,得到UploadToken:
2.代码如下
1.头文件:
#import "UploadManager.h" #import "HttpManager.h" #import <GTMBase64/GTMBase64.h> #import <CommonCrypto/CommonDigest.h> #import <CommonCrypto/CommonHMAC.h>
2.获取上传凭证(token)
- (NSString *)makeToken:(NSString *)accessKey secretKey:(NSString *)secretKey bucket:(NSString *)bucket key:(NSString *)key { const char *secretKeyStr = [secretKey UTF8String]; NSString *policy = [self marshal: bucket key:key]; NSData *policyData = [policy dataUsingEncoding:NSUTF8StringEncoding]; NSString *encodedPolicy = [GTMBase64 stringByWebSafeEncodingData:policyData padded:TRUE]; const char *encodedPolicyStr = [encodedPolicy cStringUsingEncoding:NSUTF8StringEncoding]; char digestStr[CC_SHA1_DIGEST_LENGTH]; bzero(digestStr, 0); CCHmac(kCCHmacAlgSHA1, secretKeyStr, strlen(secretKeyStr), encodedPolicyStr, strlen(encodedPolicyStr), digestStr); NSString *encodedDigest = [GTMBase64 stringByWebSafeEncodingBytes:digestStr length:CC_SHA1_DIGEST_LENGTH padded:TRUE]; NSString *token = [NSString stringWithFormat:@"%@:%@:%@", accessKey, encodedDigest, encodedPolicy]; return token;//得到了token }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545 }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545; min-height: 14.0px }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px ".PingFang SC"; color: #454545 }
span.s1 { font: 12.0px ".PingFang SC" }
span.s2 { font: 12.0px "Helvetica Neue" }
- (NSString *)marshal:(NSString *)bucket key:(NSString *)key
{
time_t deadline;
time(&deadline);//返回当前系统时间
//@property (nonatomic , assign) int expires; 怎么定义随你...
deadline += (_expires > 0) ? _expires : 3600; // +3600秒,即默认token保存1小时.
NSNumber *deadlineNumber = [NSNumber numberWithLongLong:deadline];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//images是我开辟的公共空间名(即bucket),aaa是文件的key,
//按七牛“上传策略”的描述: <bucket>:<key>,表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”,若已存在同名资源则会被覆盖。如果只希望上传指定key的文件,并且不允许修改,那么可以将下面的 insertOnly 属性值设为 1。
//所以如果参数只传users的话,下次上传key还是aaa的文件会提示存在同名文件,不能上传。
//传images:aaa的话,可以覆盖更新,但实测延迟较长,我上传同名新文件上去,下载下来的还是老文件。
NSString *value = [NSString stringWithFormat:@"%@:%@", bucket, key];
[dic setObject:value forKey:@"scope"];//根据
[dic setObject:deadlineNumber forKey:@"deadline"];
NSString *json = [dic mj_JSONString];
return json;
}
三:上传
有了上传token,上传so easy.
for (UploadTask *task in _tasks) { if (task.fileURL != nil) continue; dispatch_group_enter(_group); dispatch_async(_queue, ^{ QNUploadOption * option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) { progress(key,percent); }]; QNUploadManager *upManager = [[QNUploadManager alloc] init]; [upManager putData:task.data key:key token:_upimagetoken complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) { NSLog(@"uploadWithKey:七牛返回数据: %@", info); if (kQNInvalidToken == info.statusCode) { _upimagetoken = nil; } NSString *respKey = resp[@"key"]; //_keyStr = respKey; if (respKey) { NSString* fileUrl = [_img_host stringByAppendingString:respKey]; [task updateFileURL:fileUrl fileKey:respKey]; dispatch_group_leave(_group); }else{ NSError *error = [NSError errorWithDomain:@"com.fdzx" code:-1 userInfo:@{}]; [task updateError:error]; dispatch_group_leave(_group); } } option:option]; dispatch_group_notify(_group, dispatch_get_main_queue(), ^{ _completionHandler(_tasks); });
四.下载更easy
根据七牛的下载凭证文档
下载均使用GET方法
get的URL生成方法看一下文档就行,分私有空间和公共空间两种。
-(void)download { NSString *path = @"自己查看一下文档,这里填你需要下载的文件的url"; NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:path] cachePolicy:1 timeoutInterval:15.0f]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSLog(@"response = %@",response); //得到了JSON文件 解析就好了。 id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; NSLog(@"%@", result); }]; }